IT TIP

객체 배열 선언

itqueen 2020. 10. 18. 19:54
반응형

객체 배열 선언


배열 인 변수가 있고 배열의 모든 요소가 기본적으로 개체로 작동하기를 원합니다. 이를 달성하기 위해 코드에서 이와 같은 작업을 수행 할 수 있습니다.

var sample = new Array();
sample[0] = new Object();
sample[1] = new Object();

이것은 잘 작동하지만 색인 번호를 언급하고 싶지 않습니다. 내 배열의 모든 요소가 객체가되기를 원합니다. 어떻게 선언하거나 초기화합니까?

var sample = new Array();
sample[] = new Object();

위의 코드를 시도했지만 작동하지 않습니다. 인덱스 번호를 사용하지 않고 객체 배열을 어떻게 초기화합니까?


array.push()배열 끝에 항목을 추가하는 데 사용 합니다.

var sample = new Array();
sample.push(new Object());

n시간 을 수행하려면 for루프를 사용하십시오 .

var n = 100;
var sample = new Array();
for (var i = 0; i < n; i++)
    sample.push(new Object());

당신은 또한 대체 할 수 있습니다 new Array()[]new Object(){}가가되도록 :

var n = 100;
var sample = [];
for (var i = 0; i < n; i++)
    sample.push({});

선언의 의미에 따라 배열 리터럴 에서 객체 리터럴사용해 볼 수 있습니다 .

var sample = [{}, {}, {} /*, ... */];

편집 : 목표가 undefined항목이 기본적으로 빈 개체 리터럴 인 배열 인 경우 작은 유틸리티 함수를 작성할 수 있습니다.

function getDefaultObjectAt(array, index)
{
    return array[index] = array[index] || {};
}

그런 다음 다음과 같이 사용하십시오.

var sample = [];
var obj = getDefaultObjectAt(sample, 0);     // {} returned and stored at index 0.

또는:

getDefaultObjectAt(sample, 1).prop = "val";  // { prop: "val" } stored at index 1.

물론 반환 값에 대한 직접 할당 getDefaultObjectAt()은 작동하지 않으므로 다음과 같이 작성할 수 없습니다.

getDefaultObjectAt(sample, 2) = { prop: "val" };

댓글에서 어떻게 응답했는지 확인한 후. push다른 사람들이 제안한대로 사용하는 것이 가장 좋을 것 같습니다 . 이렇게하면 인덱스를 알 필요가 없지만 배열에 추가 할 수 있습니다.

var arr = [];
function funcInJsFile() {
    // Do Stuff
    var obj = {x: 54, y: 10};
    arr.push(obj);
}

이 경우 해당 함수를 사용할 때마다 새 개체를 배열로 푸시합니다.


공백을 만들 필요가 없습니다 Object. 당신은 그들과 함께 아무것도 할 수 없습니다. 필요에 따라 샘플에 작업 개체를 추가하기 만하면됩니다. 사용 push다니엘 Imms으로 제안하고, 프레데릭 Hamidi로 사용 리터럴은 제안했다. C와 같은 Javascript를 프로그래밍하고 싶은 것 같습니다.

var samples = []; /* If you have no data to put in yet. */
/* Later, probably in a callback method with computed data */
/* replacing the constants. */
samples.push(new Sample(1, 2, 3)); /* Assuming Sample is an object. */
/* or */
samples.push({id: 23, chemical: "NO2", ppm: 1.4}); /* Object literal. */

사용 new Array(10)하면 10 개의 undefined요소 가있는 배열이 생성 됩니다.


다음과 같이 "객체 유형"배열을 다음과 같이 한 줄로 인스턴스화 할 수 있습니다 ( new Object () 를 객체로 바꾸면됩니다).

var elements = 1000;
var MyArray = Array.apply(null, Array(elements)).map(function () { return new Object(); });

fill () 사용할 수 있습니다 .

let arr = new Array(5).fill('lol');
// or if you want different objects
let arr2 = new Array(5).fill().map(x => ({ test: 'a' }));

5 개 항목의 배열을 생성합니다. 예를 들어 forEach를 사용할 수 있습니다.

arr.forEach(str => console.log(str));

그럼 array.length트릭을 할 여부를해야합니까? 그냥 읽으면 인덱스 범위를 알 필요가 없다는 뜻입니다 ..

var arrayContainingObjects = [];
for (var i = 0; i < arrayContainingYourItems.length; i++){
    arrayContainingObjects.push {(property: arrayContainingYourItems[i])};
}

질문을 올바르게 이해하지 못했을 수도 있지만 이런 식으로 배열의 길이를 가져와 객체로 변환 할 수 있어야합니다. 다니엘은 정직하게 같은 대답을했습니다. 배열 길이를 그의 변수에 저장하면 완료됩니다.

내 의견으로는 이것이 일어나지 않아야한다면 Array-length를 얻을 수 없습니다. 색인 번호를 얻지 않고 말했듯이 다음과 같이 할 수 있습니다.

var arrayContainingObjects = [];
for (;;){
    try{
        arrayContainingObjects.push {(property: arrayContainingYourItems[i])};
    }
}
catch(err){
    break;
}

위 버전의 좋지 않은 버전이지만 인덱스 범위를 "실행"할 때까지 루프가 실행됩니다.


이 시도-

var arr = [];
arr.push({});

//making array of book object
var books = [];
    var new_book = {id: "book1", name: "twilight", category: "Movies", price: 10};
    books.push(new_book);
    new_book = {id: "book2", name: "The_call", category: "Movies", price: 17};
    books.push(new_book);
    console.log(books[0].id);
    console.log(books[0].name);
    console.log(books[0].category);
    console.log(books[0].price);

// also we have array of albums
var albums = []    
    var new_album = {id: "album1", name: "Ahla w Ahla", category: "Music", price: 15};
    albums.push(new_album);
    new_album = {id: "album2", name: "El-leila", category: "Music", price: 29};
    albums.push(new_album);
//Now, content [0] contains all books & content[1] contains all albums
var content = [];
content.push(books);
content.push(albums);
var my_books = content[0];
var my_albums = content[1];
console.log(my_books[0].name);
console.log(my_books[1].name); 

console.log(my_albums[0].name);
console.log(my_albums[1].name); 

이 예제는 나와 함께 작동합니다. 브라우저 콘솔의 출력에 대한 스냅 샷


array.push ()를 사용하여 배열 끝에 항목을 추가합니다.

var sample = new Array();
sample.push(new Object());

당신은 그것을 사용할 수 있습니다

var x = 100;
var sample = [];
for(let i=0; i<x ;i++){
  sample.push({}) 
  OR
  sample.push(new Object())
}    

forEach를 사용하면 데이터에 대해 비즈니스 로그인을 수행하려는 데이터가 이미있는 경우 데이터를 저장할 수 있습니다.

var sample = new Array();
var x = 10;
var sample = [1,2,3,4,5,6,7,8,9];
var data = [];

sample.forEach(function(item){
    data.push(item);
})

document.write(data);

간단한 for 루프를 사용한 예

var data = [];
for(var i = 0 ; i < 10 ; i++){
   data.push(i);
}
document.write(data);

If you want all elements inside an array to be objects, you can use of JavaScript Proxy to apply a validation on objects before you insert them in an array. It's quite simple,

const arr = new Proxy(new Array(), {
  set(target, key, value) {
    if ((value !== null && typeof value === 'object') || key === 'length') {
      return Reflect.set(...arguments);
    } else {
      throw new Error('Only objects are allowed');
    }
  }
});

Now if you try to do something like this:

arr[0] = 'Hello World'; // Error

It will throw an error. However if you insert an object, it will be allowed:

arr[0] = {}; // Allowed

For more details on Proxies please refer to this link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

If you are looking for a polyfill implementation you can checkout this link: https://github.com/GoogleChrome/proxy-polyfill


The below code from my project maybe you good for you

  reCalculateDetailSummary(updateMode: boolean) {

    var summaryList: any = [];
    var list: any;
    if (updateMode) { list = this.state.pageParams.data.chargeDefinitionList }
    else {
        list = this.state.chargeDefinitionList;
    }

    list.forEach((item: any) => {
        if (summaryList == null || summaryList.length == 0) {
            var obj = {
                chargeClassification: item.classfication,
                totalChargeAmount: item.chargeAmount
            };
            summaryList.push(obj);

        } else {
            if (summaryList.find((x: any) => x.chargeClassification == item.classfication)) {
                summaryList.find((x: any) => x.chargeClassification == item.classfication)
                    .totalChargeAmount += item.chargeAmount;
            }
        }
    });

    if (summaryList != null && summaryList.length != 0) {
        summaryList.push({
            chargeClassification: 'Total',
            totalChargeAmount: summaryList.reduce((a: any, b: any) => a + b).totalChargeAmount
        })
    }

    this.setState({ detailSummaryList: summaryList });
}

const sample = [];
    list.forEach(element => {
      const item = {} as { name: string, description: string };
      item.name= element.name;
      item.description= element.description;
      result.push(item);
    });
    return sample;

Anyone try this.. and suggest something.


var ArrayofObjects = [{}]; //An empty array of objects.

참고URL : https://stackoverflow.com/questions/15742442/declaring-array-of-objects

반응형