Declaring array of objects

前端 未结 15 1328
遇见更好的自我
遇见更好的自我 2020-12-02 07:01

I have a variable which is an array and I want every element of the array to act as an object by default. To achieve this, I can do something like this in my code.



        
相关标签:
15条回答
  • 2020-12-02 07:38

    You don't really need to create blank Objects ever. You can't do anything with them. Just add your working objects to the sample as needed. Use push as Daniel Imms suggested, and use literals as Frédéric Hamidi suggested. You seem to want to program Javascript like C.

    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. */
    

    I believe using new Array(10) creates an array with 10 undefined elements.

    0 讨论(0)
  • 2020-12-02 07:44

    You can use fill().

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

    Will create an array of 5 items. Then you can use forEach for example.

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

    Note that when doing new Array(5) it's just an object with length 5 and the array is empty. When you use fill() you fill each individual spot with whatever you want.

    0 讨论(0)
  • 2020-12-02 07:44
    const sample = [];
        list.forEach(element => {
          const item = {} as { name: string, description: string };
          item.name= element.name;
          item.description= element.description;
          sample.push(item);
        });
        return sample;
    

    Anyone try this.. and suggest something.

    0 讨论(0)
  • 2020-12-02 07:46

    Depending on what you mean by declaring, you can try using object literals in an array literal:

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

    EDIT: If your goal is an array whose undefined items are empty object literals by default, you can write a small utility function:

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

    Then use it like this:

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

    Or even:

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

    Of course, direct assignment to the return value of getDefaultObjectAt() will not work, so you cannot write:

    getDefaultObjectAt(sample, 2) = { prop: "val" };
    
    0 讨论(0)
  • 2020-12-02 07:46

    After seeing how you responded in the comments. It seems like it would be best to use push as others have suggested. This way you don't need to know the indices, but you can still add to the array.

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

    In this case, every time you use that function, it will push a new object into the array.

    0 讨论(0)
  • 2020-12-02 07:46
    //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); 
    

    This Example Works with me. Snapshot for the Output on Browser Console

    0 讨论(0)
提交回复
热议问题