简体   繁体   English

映射数组中对象中的数组

[英]Mapping over arrays in objects in arrays

I have a data structure like this: 我有这样的数据结构:

let foo = [{ "a": [1,2,3] }]

I want to map over the array inside the object, inside this array 我想映射对象内部的数组,在这个数组中

// Approach 1:
foo.map(foo => foo.a.map(val => val + 1))

This returns [ [ 2,3,4 ] ] but removes the outer object (which I consider quite interesting). 这返回[ [ 2,3,4 ] ]但删除了外部对象(我认为非常有趣)。

// Approach 2:
foo.map(foo => {
    foo.a = foo.a.map(val => val + 1)
    return foo
})

This works, but also changes the object itself. 这有效,但也会改变对象本身。

Is there some way to do this, that returns the correct value, but doesn't change the object given as an argument? 有没有办法做到这一点,返回正确的值,但不会更改作为参数给出的对象?

EDIT: 编辑:

My use case includes having multiple objects in this array: 我的用例包括在这个数组中有多个对象:

let bar = [
    { "a": [1,2,3] },
    { "a": [5,5,5] },
    { "a": [10,100,1000] },
]

So just addressing the array inside directly doesn't really help. 所以直接解决内部的数组并没有多大帮助。

You can return copy of original object using Object.assign() and add modified a array. 您可以使用Object.assign()返回原始对象的副本,并添加已修改a数组。

 let bar = [ { "a": [1,2,3]}, { "a": [5,5,5] }, { "a": [10,100,1000] }, ] let result = bar.map(function(e) { return Object.assign({}, e, {a: eamap(a => a + 1)}) }) console.log(bar) console.log(result) 

You could iterate all entries of the object and return a new array with all objects and an incremented array. 您可以迭代对象的所有条目,并返回包含所有对象和递增数组的新数组。

 let foo = [{ a: [1, 2, 3] }, { b: [7, 8, 9] }], result = foo.map(o => Object.assign({}, ...Object.entries(o).map(([k, v]) => ({ [k]: v.map(b => b + 1) })))); console.log(result); console.log(foo); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

I would advise you to be careful when using Object.assign() since it will break the reference to the objects in foo if it's first argument is an empty object. 我建议你在使用Object.assign()时要小心,因为如果它的第一个参数是一个空对象,它会破坏对foo对象的引用。 Depending on the case this may or may not what you wanted. 根据具体情况,这可能是您想要的,也可能不是。

If you want to keep the reference you may simply do as follows; 如果你想保留参考,你可以简单地做如下;

 var foo = [{ "a": [1,2,3]}], bar = foo.map(o => (oa = oamap(val => val + 1),o)); console.log(bar); foo[0].x = "whatever"; console.log(foo); console.log(bar); 

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

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