[英]Lodash way of adding property to object
I have an object我有一个对象
{ id1: {name: 'John'}, id2: {name: 'Mary'} }
I need to assign
a property to each person.我需要为每个人assign
一个财产。 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.我可以通过forEach
在_.values
做到这一点,但这似乎不是最好的方法。 Is there a LoDash way to do this有没有LoDash方法来做到这一点
use _.mapValues
使用_.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...? ES6 版本,可能也是最快的...?
var obj = { id1: {name: 'John'}, id2: {name: 'Mary'} } for (let [key, val] of Object.entries(obj)) val.married = false console.log(obj)
Use _.mapValues,使用 _.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}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.