1

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.

1
  • 1
    foo[0].a.map(val => val + 1) Commented Mar 25, 2017 at 10:21

3 Answers 3

1

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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; }

Comments

1

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

3 Comments

By "breaking the reference" you mean copying the data structure? In this case I want to treat the object more as a data structure rather than an object, so I'm fine with this.
Also, I didn't know, you could write arrow functions like this, that's awesome!
@hgiesel Sorry i have corrected by wording about the Object.assign() referencing in my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.