البرمجة

اختيار الحقول من كائنات المصفوفة في JavaScript

To achieve this using lodash, you can use the _.map function along with _.pick to select specific fields from each object in the array. Here’s how you can do it:

javascript
var _ = require('lodash'); var results = [ { "_type": "MyType", "_id": "57623535a44b8f1417740a13", "_source": { "info": { "year": 2010, "number": "string" }, "type": "stolen", "date": "2016-06-16T00:00:00", "createdBy": "57469f3c71c8bf2479d225a6" } } ]; var res = _.map(results, function(obj) { return _.pick(obj, ['_id', '_source']); }); console.log(res);

This will output the desired result:

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

In this code, _.map is used to iterate over each object in the results array. For each object, _.pick is used to select the _id field and the content of the _source object.

المزيد من المعلومات

للقيام بذلك باستخدام لوداش، يمكنك استخدام دالة _.map بالاشتراك مع دالة _.pick لتحديد الحقول المحددة من كل كائن في المصفوفة. هنا كيف يمكنك القيام بذلك:

javascript
var _ = require('lodash'); var results = [ { "_type": "MyType", "_id": "57623535a44b8f1417740a13", "_source": { "info": { "year": 2010, "number": "string" }, "type": "stolen", "date": "2016-06-16T00:00:00", "createdBy": "57469f3c71c8bf2479d225a6" } }, { "_type": "AnotherType", "_id": "57623535a44b8f1417740a14", "_source": { "info": { "year": 2011, "number": "another string" }, "type": "lost", "date": "2017-06-16T00:00:00", "createdBy": "57469f3c71c8bf2479d225a7" } } ]; var res = _.map(results, function(obj) { return _.pick(obj, ['_id', '_source']); }); console.log(res);

هذا سينتج النتيجة المرجوة:

javascript
[ { "_id": "57623535a44b8f1417740a13", "_source": { "info": { "year": 2010, "number": "string" }, "type": "stolen", "date": "2016-06-16T00:00:00", "createdBy": "57469f3c71c8bf2479d225a6" } }, { "_id": "57623535a44b8f1417740a14", "_source": { "info": { "year": 2011, "number": "another string" }, "type": "lost", "date": "2017-06-16T00:00:00", "createdBy": "57469f3c71c8bf2479d225a7" } } ]

في هذا الكود، تُستخدم _.map للتكرار على كل كائن في مصفوفة results. لكل كائن، يُستخدم _.pick لتحديد الحقل _id ومحتوى الكائن _source.

زر الذهاب إلى الأعلى