I have an object
{ id1: {name: 'John'}, id2: {name: 'Mary'} }
I need to assign
a property to each person. I need to achieve this
{ id1: {name: 'John', married: false}, id2: {name: 'Mary', married: false} }
I can do it by forEach
over the _.values
but it doesn't seem like the best way. Is there a LoDash way to do this
I have an object
{ id1: {name: 'John'}, id2: {name: 'Mary'} }
I need to assign
a property to each person. I need to achieve this
{ id1: {name: 'John', married: false}, id2: {name: 'Mary', married: false} }
I can do it by forEach
over the _.values
but it doesn't seem like the best way. Is there a LoDash way to do this
3 Answers
Reset to default 5use _.mapValues
var res = _.mapValues(data, function(val, key) {
val.married = false;
return val;
})
to prevent the mutation of the original data
var res = _.mapValues(data, function(val, key) {
return _.merge({}, val, {married: false});
})
to mutate in place
_.mapValues(data, function(val, key) {
val.married = false;
})
ES6 version, probably also the fastest...?
var obj = { id1: {name: 'John'}, id2: {name: 'Mary'} }
for (let [key, val] of Object.entries(obj))
val.married = false
console.log(obj)
Use _.mapValues,
let rows = { id1: {name: 'John'}, id2: {name: 'Mary'} };
_.mapValues(rows, (value, key) => {
value.married = false;
});
Output:-
{id1: {name: "John", married: false}, id2: {name: "Mary", married: false}}