简体   繁体   中英

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. 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:

{
  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.

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

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

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
})

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