简体   繁体   中英

reset array of objects with lodash

How can i reset the properties of objects in array that are diferent from 'db'? I need to set others than 'db' to empty string.

var arr =   [
  {
    "db": "RHID",
    "prv_value": "1",
    "nxt_value": "1",
    "diagnostic": "1"
  },
  {
    "db": "CD_DOC_ID",
    "prv_value": "2",
    "nxt_value": "2",
    "diagnostic": "2"
  },
  ...
]

Use the map function, it takes an array and a transformation function. It passes each element into the function for modification.

_.map(arr, function(curr) {
    for (var prop in curr) {
        // Please read http://phrogz.net/death-to-hasownproperty
        if (curr.hasOwnProperty(prop) && prop != 'db') {
            curr[prop] = '';
        }
    } 

    return curr;
});

Here's what I would do:

_.map(arr, function(i) {
  return _.assign(
    _(i).omit('db').mapValues(_.constant('')).value(),
    _.pick(i, 'db')
  );
});

Essentially, this uses map() to create an array of new objects. It's using assign() to build the mapped object (it's basically concatenating two objects). The first argument passed to assign() is the object with the db property removed. This is done using omit() . With this property removed, we can use mapValues() to set everything back to an empty string.

Now all we have to do is add the db property back, and this is why we're using assign() . The pick() function is used to get the db value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM