Skip to content
Advertisement

Add new property to object collection based on condition with lodash

I have an array of objects as such:

var data = [{ a: 1 },
            { a: 1 },
            { a: 2 },
            { a: 2 }];

How can I create, with lodash, a new array just like data but for which we added a new property b: 1 to each object that has the property a equal to 1?

The new array should be like this:

var newdata = [{ a: 1, b: 1 },
               { a: 1, b: 1 },
               { a: 2 },
               { a: 2 }];

I guess we could combine both _.assign and _.filer but I’m not sure how.

Advertisement

Answer

You can do this with lodash via either _.defaults or _.assign / _.assignIn / _.extend:

var data = [{ a: 1 },{ a: 1 },{ a: 2 },{ a: 2 }];

console.log(_.map(data, x => x.a==1 ? _.defaults(x, {b: 1}) : x))
console.log(_.map(data, x => x.a==1 ? _.assign(x, {b: 1}) : x))
console.log(_.map(data, x => x.a==1 ? _.assignIn(x, {b: 1}) : x))
console.log(_.map(data, x => x.a==1 ? _.extend(x, {b: 1}) : x))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement