简体   繁体   中英

Using the spread operator on an array with objects

I got a Javascript object which looks like this:

{
   key1: {
           itemId: "someId",
           myValue: "value"
   },
   key2: {
           itemId: "someId2",
           myValue: "value2"
   }
}

I also got an array to which I push items like this:

myArr.push({[item.itemId] : anotherDefinedObject}); //inside a loop on items

I then want to join all the items I pushed to the array to the first object. Meaning that if for example the items ids were "key3" and "key4" I would get this object:

{
   key1: {
           itemId: "someId",
           myValue: "value"
   },
   key2: {
           itemId: "someId2",
           myValue: "value2"
   },
   key3: { //the object that was added },
   key4: { //the object that was added }
}

I tried doing it with the spread operator:

return {...object, ...myArr}

But then instead of getting what I needed, I get "0", "1" and such as the keys in the new object (since 0,1 etc are the keys of the arrays).

How do I concatenate the object and the array the way I want?

const obj = {key1: 1};
const myArr = [{key2: 2}];
myArr.forEach(val => Object.assign(obj, val));

console.log(obj); // {key1: 1, key2: 2}

rather my myArray create myObject .

myObject = {}
myObject[item.itemId] = anotherDefinedObject;

Then

return {...object, ...myObject}

What you're looking to achieve here is not possible with the spread operator; it's working exactly as intended and the functionality cannot be changed as JS doesn't allow operator overloading. Your best bet is to loop through myArr and add each item in the array to the object using your own code.

PS As the comments suggest, in the future you should really provide more examples of your input, the current output, and your intended output; it was quite difficult to follow without it.

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