Reputation: 5648
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.
Upvotes: 1
Views: 66
Reputation: 26161
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 => (o.a = o.a.map(val => val + 1),o));
console.log(bar);
foo[0].x = "whatever";
console.log(foo);
console.log(bar);
Upvotes: 1
Reputation: 386540
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; }
Upvotes: 1
Reputation: 122027
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: e.a.map(a => a + 1)})
})
console.log(bar)
console.log(result)
Upvotes: 1