简体   繁体   English

我想将每个 object 的不同数组值插入到 object 内的数组中

[英]I want to insert different array values ​per object into an array inside the object

I want to insert different array values per object into an array inside the object.我想将每个 object 的不同数组值插入到 object 内的数组中。

I have an arrayDetail object.我有一个arrayDetail object。

console.log(arrayDetail)

[
    {
        "content": "stackoverflow1",
        "type": "one"
        "appleId": undefined 
    },
    {
        "content": "stackoverflow2",
        "type": "two"
        "appleId": undefined 
    }
]

I have an applesIds array.我有一个applesIds数组。

console.log(applesIds);

[49,50]

This is the result I want.这就是我想要的结果。
I tried a few times using map function or Object.fromEntries() function and looked up other stack overflow questions,我尝试了几次使用map function 或Object.fromEntries() function 并查找其他堆栈溢出问题,
but I can't get it to work.但我无法让它工作。

[
    {
        "content": "stackoverflow1",
        "type": "one"
        "appleId": 49 
    },
    {
        "content": "stackoverflow2",
        "type": "two"
        "appleId": 50 
    }
]

This would do the work这会做的工作

 let data = [ { "content": "stackoverflow1", "type": "one", "appleId": undefined }, { "content": "stackoverflow2", "type": "two", "appleId": undefined } ] let id = [49, 50] for(let i = 0; i < data.length; i++){ data[i]['appleId'] = id[i] } console.log(data)

You can use Array.map (use can use other Array iteration methods as well) and update the appleId like below您可以使用Array.map (也可以使用其他 Array 迭代方法)并更新 appleId,如下所示

 const arrayDetail = [{ "content": "stackoverflow1", "type": "one", "appleId": undefined }, { "content": "stackoverflow2", "type": "two", "appleId": undefined } ] const appleIds = [49, 50]; const result = arrayDetail.map((item, index) => { return {...item, appleId: appleIds[index] } }); console.log(result);

Single liner code map always return array so i was returning array of object and put appleId with the help of index.单行代码 map 总是返回数组,所以我返回 object 的数组,并在索引的帮助下放置 appleId。 index is 0,1,2 iteration so access id array with index索引是 0,1,2 次迭代,所以访问带有索引的 id 数组

const mappedData = data.map((item, index) => ({ ...item, appleId: id[index] }));

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

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