Home > other >  Merge array of objects inside loop into new object
Merge array of objects inside loop into new object

Time:10-29

Trying to create a new object, and then join all the objects from nested values from a JSON file.

The JSON data is rather large, so have taken a sample, and called it var items

Problem I am having is that the nested data is not updating the new object.

var items = [
    {
    "id": 11,
    "title": "Fruit Test",
    "releaseDateTime": "2021-10-21T10:50:00 09:30",
    "mainContent": "Fruit order for 1 person",
    "storeNames": [
        "Store 1"
    ],
    "items": [
        {
            "itemName": "Melon",
            "otherName": "Watermelon"
        },
        {
            "itemName": "Apple",
            "otherName": "Red apple"
        }
    ]

},
{
    "id": 12,
    "title": "Canned Test",
    "releaseDateTime": "2021-10-21T10:50:00 09:30",
    "mainContent": "Canned order for 2 people",
    "storeNames": [
        "Store 1"
    ],
    "items": [
        {
            "itemName": "Tomatoes",
            "otherName": "Diced tomato"
        }
    ]
},
{
    "id": 13,
    "title": "Dairy Test",
    "releaseDateTime": "2021-10-21T10:50:00 09:30",
    "mainContent": "Dairy Order for 2 people",
    "storeNames": [
        "Store 1"
    ],
    "items": []
}
]
;

var copyItems = [];


for (let i = 0; i < items.length; i  ) {
items[i].allItems = items[i].items;
  copyItems.push(items[i])
}

console.log(copyItems);


var copyItems = copyItems.map(function(elem){
    return elem.allItems;
}).join(",");

console.log(`These are the final items ${copyItems}`);

I am able to create the new object, and add the nested arrays to this. However I am trying to get the allItems object to display the information like the following:

[
    {
    "id": 11,
    "allItems": "Melon, Apple",
    "title": "Fruit Test",
    "releaseDateTime": "2021-10-21T10:50:00 09:30",
    "mainContent": "Fruit order for 1 person",
    "storeNames": [
        "Store 1"
    ],
    "items": [
        {
            "itemName": "Melon",
            "otherName": "Watermelon"
        },
        {
            "itemName": "Apple",
            "otherName": "Red apple"
        }
    ]

},
{
    "id": 12,
    "allItems": "Tomatoes",
    "title": "Canned Test",
    "releaseDateTime": "2021-10-21T10:50:00 09:30",
    "mainContent": "Canned order for 2 people",
    "storeNames": [
        "Store 1"
    ],
    "items": [
        {
            "itemName": "Tomatoes",
            "otherName": "Diced tomato"
        }
    ]
},
{
    "id": 13,
    "allItems": "",
    "title": "Dairy Test",
    "releaseDateTime": "2021-10-21T10:50:00 09:30",
    "mainContent": "Dairy Order for 2 people",
    "storeNames": [
        "Store 1"
    ],
    "items": []
}
]

Here is my JSFiddle: https://jsfiddle.net/buogdvx9/6/

Javascript is still a language I am learning and working through, and some things still catch me out.

Thank you.

CodePudding user response:

You can use Array.map() to create the new array, then using some destructuring to create each new element in this array.

We create the allitems property on each new element by first mapping the sub items array to get a list of subitem names, then using Array.join() to create a comma separated string.

The arrow function you see as the first argument to Array.map is another way of writing function(args) { .. }.

const items = [ { "id": 11, "title": "Fruit Test", "releaseDateTime": "2021-10-21T10:50:00 09:30", "mainContent": "Fruit order for 1 person", "storeNames": [ "Store 1" ], "items": [ { "itemName": "Melon", "otherName": "Watermelon" }, { "itemName": "Apple", "otherName": "Red apple" } ]  }, { "id": 12, "title": "Canned Test", "releaseDateTime": "2021-10-21T10:50:00 09:30", "mainContent": "Canned order for 2 people", "storeNames": [ "Store 1" ], "items": [ { "itemName": "Tomatoes", "otherName": "Diced tomato" } ] }, { "id": 13, "title": "Dairy Test", "releaseDateTime": "2021-10-21T10:50:00 09:30", "mainContent": "Dairy Order for 2 people", "storeNames": [ "Store 1" ], "items": [] } ];

const result = items.map(({ id, ...rest}) => { 
    return { 
      id,
      allItems: rest.items.map(el => el.itemName).join(', '), 
      ...rest
    };
});

console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Since you only want to update the existing object, using forEach to loop over each item in array, then loop over the prosperity with a map operator to get the array with itemName.

  items.forEach((obj) => {
      
      obj.allItems = obj.items.map((item) => item.itemName)
    });
    
    console.log(items)

Simple example:

   // iterating over the items
 for (let i = 0; i < items.length; i  ) {
  
    let currentItem = items[i];
  
    currentItem.allItems = []; // adding new empty array
  
    for (let j = 0; j < currentItem.items.length; j  ) {
      
        currentItem.allItems.push(currentItem.items[j].itemName);
    }

}

Working Example:

var items = [
    {
    "id": 11,
    "title": "Fruit Test",
    "releaseDateTime": "2021-10-21T10:50:00 09:30",
    "mainContent": "Fruit order for 1 person",
    "storeNames": [
        "Store 1"
    ],
    "items": [
        {
            "itemName": "Melon",
            "otherName": "Watermelon"
        },
        {
            "itemName": "Apple",
            "otherName": "Red apple"
        }
    ]

},
{
    "id": 12,
    "title": "Canned Test",
    "releaseDateTime": "2021-10-21T10:50:00 09:30",
    "mainContent": "Canned order for 2 people",
    "storeNames": [
        "Store 1"
    ],
    "items": [
        {
            "itemName": "Tomatoes",
            "otherName": "Diced tomato"
        }
    ]
},
{
    "id": 13,
    "title": "Dairy Test",
    "releaseDateTime": "2021-10-21T10:50:00 09:30",
    "mainContent": "Dairy Order for 2 people",
    "storeNames": [
        "Store 1"
    ],
    "items": []
}
]
;
// since you only want to update the existing object, using map to loop over each item in array
items.forEach((obj) => {
  // using map to create the new array of just itemNames
  obj.allItems = obj.items.map((item) => item.itemName)
});

console.log(items)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Just use the combination of Array.map and Array.join

Logic

  • Since you want to create a new array, run Array.map on the parent array.
  • On each nodes in the parent return the whole node with one extra key allItems.
  • For allItems create a new array from items array in each node and join then with space

var items = [{"id":11,"title":"Fruit Test","releaseDateTime":"2021-10-21T10:50:00 09:30","mainContent":"Fruit order for 1 person","storeNames":["Store 1"],"items":[{"itemName":"Melon","otherName":"Watermelon"},{"itemName":"Apple","otherName":"Red apple"}]},{"id":12,"title":"Canned Test","releaseDateTime":"2021-10-21T10:50:00 09:30","mainContent":"Canned order for 2 people","storeNames":["Store 1"],"items":[{"itemName":"Tomatoes","otherName":"Diced tomato"}]},{"id":13,"title":"Dairy Test","releaseDateTime":"2021-10-21T10:50:00 09:30","mainContent":"Dairy Order for 2 people","storeNames":["Store 1"],"items":[]}];
const newItems = items.map(node => ({ ...node, allItems: node.items.map(item => item.itemName).join(" ")}));
console.log(newItems);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related