简体   繁体   中英

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).

// 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.

 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. 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); 

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