programing

개체를 배열에 푸시하려면 어떻게 해야 합니까?

lovejava 2023. 3. 10. 20:59

개체를 배열에 푸시하려면 어떻게 해야 합니까?

간단한 건 알지만 이해가 안 돼요

코드는 다음과 같습니다.

// My object
const nieto = {
  label: "Title",
  value: "Ramones" 
}

let nietos = [];
nietos.push(nieto.label);
nietos.push(nieto.value);

이렇게 하면 심플한 어레이를 얻을 수 있습니다.

["Title", "Ramones"]

다음을 작성해야 합니다.

[{"01":"Title", "02": "Ramones"}]

사용방법push()오브젝트를 에 추가하다nietos어레이?

개체를 만들어야 합니다.개체에 값을 할당합니다.다음으로 어레이에 푸시합니다.

var nietos = [];
var obj = {};
obj["01"] = nieto.label;
obj["02"] = nieto.value;
nietos.push(obj);

다음과 같은 개체 배열을 만듭니다.

var nietos = [];
nietos.push({"01": nieto.label, "02": nieto.value});
return nietos;

먼저 푸시 메서드 내부에 개체를 생성한 다음 새로 생성된 배열을 반환합니다.

이렇게도 할 수 있어요.

// our object array
let data_array = [];

// our object
let my_object = {}; 
   
// load data into object

my_object.name = "stack";
my_object.age = 20;
my_object.hair_color = "red";
my_object.eye_color = "green";
        
// push the object to Array
data_array.push(my_object);

디스커버리 할당 사용(ES6)

const nieto = {label: 'title', value: 'ramones' } 
const modifiedObj = {01: nieto.label, 02: nieto.value}

let array = [
  {03: 'asd', 04: 'asd'}, 
  {05: 'asd', 06: 'asd'} 
]

// push the modified object to the first index of the array
array = [modifiedObj, ...array] 

console.log(array)

변경된 개체를 어레이의 마지막 인덱스로 푸시하려면 구조화되지 않은 어레이를 변경하기만 하면 됩니다....array앞으로.

array = [...array, modifiedObj]

음.["Title", "Ramones"]는 문자열 배열입니다.그렇지만[{"01":"Title", "02", "Ramones"}]는 객체의 배열입니다.

속성 또는 값을 하나의 객체에 푸시하려면 해당 객체에 액세스한 다음 데이터를 해당 객체에 푸시해야 합니다.예:nietos[indexNumber].yourProperty=yourValue;실제 응용 프로그램:

nietos[0].02 = "Ramones";

개체 배열이 이미 비어 있는 경우 해당 배열에 하나 이상의 개체 또는 데이터를 푸시할 개체가 있는지 확인하십시오.

예를 들어 어레이는myArray[]즉, 이것은 빈 배열입니다.JS 엔진은 문자열, 객체, 번호 0이 아닌 어떤 유형의 데이터를 가지고 있는지 알 수 없습니다.따라서 객체(빈 객체)를 해당 어레이에 푸시합니다. myArray.push({}), 또는myArray.push({""}).

그러면 빈 객체가 에 푸시됩니다.myArray인덱스 번호를 갖게 될 것입니다.0그럼, 당신의 정확한 목표는myArray[0]

그럼 밀어주세요property그리고.value이렇게 만들 수 있습니다.

myArray[0].property = value;
//in your case:
myArray[0]["01"] = "value";

잘 모르겠지만, 다음과 같이 시도해 보세요.

var pack = function( arr ) {
    var length = arr.length,
        result = {},
        i;

    for ( i = 0; i < length; i++ ) {
        result[ ( i < 10 ? '0' : '' ) + ( i + 1 ) ] = arr[ i ];
    }

    return result;
};

pack( [ 'one', 'two', 'three' ] ); //{01: "one", 02: "two", 03: "three"}

아래의 솔루션은 보다 간단합니다.두 개의 지정된 항목에서 개체를 "작성"할 수 있는 하나의 간단한 함수를 정의하기만 하면 됩니다.그런 다음 객체를 생성하고 resultArray에 저장할 요소가 있는 2개의 어레이에 이 기능을 적용하기만 하면 됩니다.

var arr1 = ['01','02','03'];
var arr2 = ['item-1','item-2','item-3'];
resultArray = [];
    for (var j=0; j<arr1.length; j++) {
        resultArray[j] = new makeArray(arr1[j], arr2[j]);
    }
function makeArray(first,second) {
    this.first = first;
    this.second = second;
}

이 솔루션은 모든 개체에 3개 이상의 속성이 있을 때 사용할 수 있습니다.

const nieto = {
  label: "Title",
  value: "Ramones" 
}

let nietos = [];

let xyz = Object.entries(nieto)

xyz.forEach((i,j)=>{
    i[0] = `${(j+1).toLocaleString("en-US", {
        minimumIntegerDigits: 2,
        useGrouping: false,
      })}`
})

nietos.push(Object.fromEntries(xyz))

언급URL : https://stackoverflow.com/questions/40250139/how-can-i-push-an-object-into-an-array