简体   繁体   English

用lodash重置对象数组

[英]reset array of objects with lodash

How can i reset the properties of objects in array that are diferent from 'db'? 如何重置与“ db”不同的数组对象的属性? I need to set others than 'db' to empty string. 我需要将除“ db”以外的其他值设置为空字符串。

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. 使用map函数,它需要一个数组和一个转换函数。 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. 本质上,这使用map()创建新对象的数组。 It's using assign() to build the mapped object (it's basically concatenating two objects). 它使用assign()来构建映射对象(它基本上是串联两个对象)。 The first argument passed to assign() is the object with the db property removed. 传递给assign()的第一个参数是删除了db属性的对象。 This is done using omit() . 这是使用omit()完成的 With this property removed, we can use mapValues() to set everything back to an empty string. 删除此属性后,我们可以使用mapValues()将所有内容设置回空字符串。

Now all we have to do is add the db property back, and this is why we're using assign() . 现在,我们要做的就是重新添加db属性,这就是为什么我们使用assign() The pick() function is used to get the db value. pick()函数用于获取db值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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