Javascript lodash 从数组中选取对象字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37877860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:50:36  来源:igfitidea点击:

lodash pick object fields from array

javascriptlodash

提问by user348173

I have array of objects:

我有对象数组:

var results= [
    {         
      "_type": "MyType",
      "_id": "57623535a44b8f1417740a13",         
      "_source": {
        "info": {
          "year": 2010,
          "number": "string",             
        },
        "type": "stolen",           
        "date": "2016-06-16T00:00:00",
        "createdBy": "57469f3c71c8bf2479d225a6"            
      }
    }
  ];

I need to select specific fields from array. In result, I want to get the following:

我需要从数组中选择特定的字段。结果,我想得到以下内容:

[
    {
        "_id": "57623535a44b8f1417740a13",
        "info": {
            "year": 2010,
            "number": "string"
        },
        "type": "stolen",            
        "date": "2016-06-16T00:00:00",
        "createdBy": "57469f3c71c8bf2479d225a6"
    }
]

As you can see, I want to select _idfield and content of _sourceobject. How can I do this with lodash?

如您所见,我想选择对象的_id字段和内容_source。我怎样才能用 lodash 做到这一点?

I've found .mapfunction, but it doesn't take array of keys: var res = _.map(results, "_source");

我找到了.map函数,但它不需要键数组: var res = _.map(results, "_source");

回答by radyz

You could do:

你可以这样做:

var mapped = _.map(results, _.partialRight(_.pick, ['_id', 'info', 'type', 'date', 'createdBy']));

A little explanation:

一点解释:

  1. _.map(): Expects a function which takes each item from the collection so that you can map it to something else.
  2. _.partialRight(): Takes a function which will be called later on with the its arguments appended to the end
  3. _.pick(): Gets the path specified from the object.
  1. _.map(): 需要一个函数,它从集合中获取每个项目,以便您可以将其映射到其他内容。
  2. _.partialRight(): 接受一个函数,稍后将调用该函数并将其参数附加到末尾
  3. _.pick(): 获取从对象指定的路径。

回答by Nina Scholz

In plain Javascript you could iterate with Array#mapand assemble a new object for each object without mutilation the original object.

在纯 Javascript 中,您可以迭代Array#map并为每个对象组装一个新对象,而不会破坏原始对象。

var results = [{ "_type": "MyType", "_id": "57623535a44b8f1417740a13", "_source": { "info": { "year": 2010, "number": "string", }, "type": "stolen", "date": "2016-06-16T00:00:00", "createdBy": "57469f3c71c8bf2479d225a6" } }],
    res = results.map(function (a) {
        var o = { _id: a._id };
        ["info", "type", "date", "createdBy"].forEach(function (k) {
            o[k] = a._source[k];
        });
        return o;
    });

console.log(res);

回答by Mikhail Shabrikov

var results = [{
  _type: "MyType",
  _id: "57623535a44b8f1417740a13",
  _source: {
    info: {
      year: 2010,
      number: "string",
    },
    type: "stolen",
    date: "2016-06-16T00:00:00",
    createdBy: "57469f3c71c8bf2479d225a6"
  }
}];

var rootProperty = ['_id']
var innerProperty = '_source'

var myArray = _.map(results, result => _(result)
  .pick(rootProperty)
  .assign(_.result(result, innerProperty))
  .value()
)

console.log(myArray)
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

回答by ryeballar

You can map()the result and have each item assign()the _idkey-value in an object toegether with the _sourceobject.

您可以map()结果并使每个项目assign()_id对象中的键值与_source对象一起。

results = _.map(results, item => _.assign(
  { _id: item._id }, 
  item._source
));

var results = [{
  "_type": "MyType",
  "_id": "57623535a44b8f1417740a13",
  "_source": {
    "info": {
      "year": 2010,
      "number": "string",
    },
    "type": "stolen",
    "date": "2016-06-16T00:00:00",
    "createdBy": "57469f3c71c8bf2479d225a6"
  }
}];

results = _.map(results, item => _.assign(
  { _id: item._id }, 
  item._source
));

document.write('<pre>' + JSON.stringify(results, 0, 4) + '</pre>');
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>

You may also choose to write this in plain JS:

你也可以选择用纯 JS 编写:

result = results.map(item => Object.assign(
  { _id: item._id }, item._source
));

var results = [{
  "_type": "MyType",
  "_id": "57623535a44b8f1417740a13",
  "_source": {
    "info": {
      "year": 2010,
      "number": "string",
    },
    "type": "stolen",
    "date": "2016-06-16T00:00:00",
    "createdBy": "57469f3c71c8bf2479d225a6"
  }
}];

result = results.map(item => Object.assign(
  { _id: item._id }, item._source
));

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

回答by Hardik Raval

I had the same requirement, and the below solution worked best for me.

我有同样的要求,下面的解决方案最适合我。

let users = [
{
  "_id": "5ead7783ed74d152f86de7b0",
  "first_name": "User First name 1",
  "last_name": "User Last name 1",
  "email": "[email protected]",
  "phone": 9587788888
},
{
  "_id": "5ead7b780d4bc43fd0ef92e7",
  "first_name": "User FIRST name 1",
  "last_name": "User LAST name 1",
  "email": "[email protected]",
  "phone": 9587788888
}
 ];

users = users.map(user => _.pick(user,['_id','first_name']))

console.log(users)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>