简体   繁体   中英

Javascript: Add object to Existing Array of objects with the same key not working

I am trying to add newList to the Grouped Array where the Grouped Array name is the same as the newList name . Eg to concat the "Dairy and Eggs" objects from newList to the Grouped Array . This is demonstrated in the desired output.

What I have tried:

const existingCatrgory = Grouped.findIndex(
    item => item.name === 'Spices' || 'Dairy and Eggs' || 'Produce'
);

if (existingCatrgory >= 0) {
    const findShoppingCategory = Grouped.filter(x => x.name === 'Spices' || 'Dairy and Eggs' || 'Produce')
    const merge = findShoppingCategory.map((element) => {
        return {
            ...element,
            data: element.data.concat(newList)
        };
    });
} else {
    return Grouped.concat(newList)
}

This is the newList :

const newList = [{
        data: [{
            value: "whipped cream"
        }, ],
        name: "Dairy and Eggs",
    },
    {
        data: [{
            value: "mushrooms",
        }],
        name: "Produce",
    }
]

This is the Grouped Array

const Grouped = [{
        data: [{
            value: "paprika",
        }, ],
        name: "Spices",
    },
    {
        data: [
            {value: "milk"},
            {value: "Blue cheese"},
        ],
        name: "Dairy and Eggs",
    },
];

Desired Output:

const Output = [{
    data: [
        { value: "paprika" },],
    name: "Spices",
},
{
    data: [
        { value: "milk" },
        { value: "Blue cheese" },
        { value: "whipped cream" },
    ],
    name: "Dairy and Eggs"
},
{
    data: [
        { value: "mushrooms" }
    ],
    name: "Produce",
}
];

Here's one way to do it:

 const Grouped = [{ data: [{ value: "paprika", }, ], name: "Spices" }, { data: [ {value: "milk"}, {value: "Blue cheese"}, ], name: "Dairy and Eggs" }, ]; const newList = [{ data: [{ value: "whipped cream" }, ], name: "Dairy and Eggs" }, { data: [{ value: "mushrooms", }], name: "Produce" } ] const mergedList = JSON.parse(JSON.stringify(Grouped)); newList.forEach(function(item){ let thisGroup = mergedList.filter(g => g.name == item.name); if (thisGroup.length > 0) { for (let i = 0; i < item.data.length; i++) { thisGroup[0].data.push({"value": item.data[i].value}); } } else { mergedList.push(item); } }) console.log(mergedList);

Just loop through each of the new items and check if the name already exists, if it does, append the new data.value to the existing data list. If it doesn't exist, create a new entry for the item.

As requested, I've updated the code to include taking a copy of the Grouped array and merging into that instead. As the Grouped array has a simple structure, I have used JSON to stringify and parse it back into a new array.

Here is another solution that uses findIndex and either creates a new item or adds to existing data.

newList.forEach(newItem =>{
    let index = Grouped.findIndex(item => item.name ===newItem.name)
    if(index===-1){
        Grouped.push(newItem)
    }else{
        Grouped[index].data.push(...newItem.data)
    }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM