[英]Using ES6 Syntax to Map an Array of Values to Array of Truncated Objects
I am trying to use .map()
and ES6 syntax to return a truncated version of each object in my array.我正在尝试使用.map()
和 ES6 语法返回数组中每个对象的截断版本。 I can do this to get one value from the original object passed on:我可以这样做以从传递的原始对象中获取一个值:
return dbJobs.map(job =>
job.data.modType
);
But how would I use ES6 syntax to handle taking an array of objects where each object looks like this:但是我将如何使用 ES6 语法来处理一个对象数组,其中每个对象看起来像这样:
{
id: 123,
name: "name value",
data: {
modType: "report",
category: "value"
}
}
... and return an array of objects where each object has two properties from the original objects, like this: ...并返回一个对象数组,其中每个对象都有来自原始对象的两个属性,如下所示:
{
name: "name value",
modType: "report"
}
You could use a destructuring and map objects with short hand properties .您可以使用具有简写属性的解构和映射对象。
var dbJobs = [{ id: 123, name: "name value", data: { modType: "report", category: "value" } }], result = dbJobs.map(({ name, data: { modType } }) => ({ name, modType })); console.log(result);
So with Array.prototype.map()
you can create a new structure based on its function's return value.因此,使用Array.prototype.map()
您可以根据其函数的返回值创建一个新结构。
The
map()
method creates a new array populated with the results of calling a provided function on every element in the calling array.map()
方法创建一个新数组,其中填充了对调用数组中的每个元素调用提供的函数的结果。
Think about the following:考虑以下问题:
const array = [{ id: 123, name: "name value", data: { modType: "report", category: "value" } }]; const result = array.map(e => { return { name: e.name, modeType: e.data.modType } }); console.log(result);
Or the same with destructuring:或者与解构相同:
const array = [{ id: 123, name: "name value", data: { modType: "report", category: "value" } }]; const result = array.map(({name, data: {modType}}) => { return { name, modType } }); console.log(result);
I hope that helps!我希望这有帮助!
I believe this will do what you need:我相信这会做你需要的:
let obj = [{ id: 123, name: "name value", data: { modType: "report", category: "value" } }]; let res = obj.map(item => { return { modType: item.data.modType, category: item.data.category } }); console.log(res);
You can try this simple js code你可以试试这个简单的js代码
arr = arr.map(item => {
const ob = {} // create temporary object
ob.name = item.name; // asign props from array object
ob.modType = item.data.modType; // asign props from array object
return ob // just return create object
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.