简体   繁体   English

在包含对象的数组上使用扩展运算符

[英]Using the spread operator on an array with objects

I got a Javascript object which looks like this:我有一个 Javascript object 看起来像这样:

{
   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.然后我想将我推送到数组的所有项目加入到第一个 object 中。 Meaning that if for example the items ids were "key3" and "key4" I would get this object:这意味着,例如,如果项目 id 是“key3”和“key4”,我会得到这个 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).但后来我没有得到我需要的东西,而是得到“0”、“1”等新 object 中的键(因为 0,1 等是数组的键)。

How do I concatenate the object and the array the way I want?如何以我想要的方式连接 object 和数组?

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 .而是我的myArray创建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.它完全按预期工作,并且由于 JS 不允许运算符重载,因此无法更改功能。 Your best bet is to loop through myArr and add each item in the array to the object using your own code.最好的办法是遍历 myArr 并使用您自己的代码将数组中的每个项目添加到 object。

PS As the comments suggest, in the future you should really provide more examples of your input, the current output, and your intended output; PS 正如评论所暗示的,将来您应该提供更多输入示例,当前的 output 和您的预期 output; it was quite difficult to follow without it.没有它很难理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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