最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Lodash way of adding property to object - Stack Overflow

programmeradmin3浏览0评论

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

Share Improve this question asked Dec 13, 2016 at 10:56 sanchitsanchit 2,5383 gold badges20 silver badges22 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

use _.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}}
发布评论

评论列表(0)

  1. 暂无评论