0

Is there a way to use the string notation in the _.set method to match all items in a nested array?

(e.g. hopefully similar to MongoDB's positional all operator)

const doc = {
  nested: [{a: 1}, {a: 2}, {a: 3}]
}

_.set(doc, "nested.$[].a", 5)

// console.log(doc)
// {
//   nested: [{a : 5}, {a: 5}, {a: 5}]
// }
1
  • I don't think there is any inbuild function in lodash. you have to use loop for this Commented May 4, 2020 at 9:55

1 Answer 1

1

No, you can't set every element in a nested array with the .set() method, but you can do this instead:

const doc = {
  nested: [{a: 1}, {a: 2}, {a: 3}]
}

// Your attempt.
// _.set(doc, "nested.$[].a", 5)

// Just use a .map() with .assign() instead.
const doc2 = _.assign({}, doc, {
  nested: _.map(doc.nested, (obj) => _.assign({}, obj, { a: 5 }))
});

console.log(doc2)
// {
//   nested: [{a : 5}, {a: 5}, {a: 5}]
// }
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

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

Comments

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.