简体   繁体   中英

how can I group array of values inside of an object to another array of object

I have an object with array of values


{firstName: ['John', 'Mike']}, lastName: ['Doe', 'Smith']} ,


Now i have an empty object with array


const newData = {} newData.ppl = []


how can I have this result in ppl array like: ppl = [{firstName: 'John', lastName: 'Doe'}, {firstName: 'Mike', lastName: 'Smith'}]

Iterate the firstName with Array.forEach() , and take the first name. Use the index to take the respective last name from the lastName array. Push a new object with the first and last names to the ppl array.

 const data = {firstName: ['John', 'Mike'], lastName: ['Doe', 'Smith']}; const newData = { ppl: [] }; data.firstName.forEach((firstName, i) => newData.ppl.push({ firstName, lastName: data.lastName[i] }) ); console.log(newData); 

A quick implementation with Object.entries , reduce , and forEach :

 const srcData = { firstName: ['John', 'Mike'], lastName: ['Doe', 'Smith'] }; const ppl = Object .entries(srcData) .reduce((acc, [key, values]) => { values.forEach((val, i) => { if (i >= acc.length) { acc.push({}); } acc[i][key] = val; }); return acc; }, []); console.log(ppl); 

Explanation:

  1. Use Object.entries to get turn the object into an array of key-value pairs.
  2. Use .reduce to iteratively build up the result array.
  3. Use .forEach to loop over the array of values obtained from (1), pushing an empty object to the array ( push({}) ) if the result array isn't long enough to hold all the items in the current array of values

You could get the entries and assign the properties to the same index as the array's values.

This works for any arbitrary count of properties.

 var data = { firstName: ['John', 'Mike'], lastName: ['Doe', 'Smith'] }, result = Object .entries(data) .reduce((r, [k, a]) => (a.forEach((v, i) => (r[i] = r[i] || {})[k] = v), r), []); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

using a map.

 let master = {firstName: ['John', 'Mike'], lastName: ['Doe', 'Smith']} const newData = {}; newData.ppl = master.firstName.map((f,i) => { return {firstName: f, lastName: master.lastName[i]}; }); console.log(newData.ppl); 

You can do it with Array.reduce() , Object.values() and Object.entries() like this:

 const data = { firstName: ['John', 'Mike'], lastName: ['Doe', 'Smith'] }; const ppl = Object.entries(data).reduce((acc, [key, arr]) => { arr.forEach((v, i) => (acc[i] = (acc[i] || {}))[key] = v); return acc; }, {}); const newData = { ppl: Object.values(ppl) }; console.log(newData); 

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