Multiple objects i have with common keys, am trying to group all duplicated objects and map any extra key exist in any object
Data i have like below
var array = [
{ id: 'Staging', cumulative: 16 },
{ id: 'Staging', yeasterday: 16 },
{ id: 'Staging', week: 16 },
{ id: 'Staging', yeasterday: 16 },
{ id: 'Staging1', cumulative: 16 },
{ id: 'Staging1', yeasterday: 16 },
{ id: 'Staging1', week: 16 },
];
Expected results, suppose to be below
var array = [
{ id: 'Staging', cumulative: 16, month: 16, week: 16, yeasterday: 16 },
{ id: 'Staging1', cumulative: 16, yeasterday: 16, week: 16 },
];
Use reduce
like so:
var array = [{ id: "Staging", cumulative: 16 }, { id: "Staging", yeasterday: 16 }, { id: "Staging", week: 16 }, { id: "Staging", yeasterday: 16 }, { id: "Staging1", cumulative: 16 }, { id: "Staging1", yeasterday: 16 }, { id: "Staging1", week: 16 }] var newArray = array.reduce((acc, { id, ...rest }) => { acc[id] = { ...(acc[id] || {}), ...rest }; return acc; }, {}); console.log(newArray);
You can achieve this by with Vanilla JavaScript (without any clunky external libraries such as Lodash). My approach will require you to use Array.reduce(), together with Map which is one of ES6's features. Then, we can use the spread syntax (or Array.from() ) to transform the Iterator
object (which contains the values of each element from the Map
object) into an array to obtain the format similar to the required output as stated on the question.
const arr = [ {id: "Staging", cumulative: 16}, {id: "Staging", yeasterday: 16}, {id: "Staging", week: 16}, {id: "Staging", yeasterday: 16}, {id: "Staging1", cumulative: 16}, {id: "Staging1", yeasterday: 16}, {id: "Staging1", week: 16} ] const iteratorMap = arr.reduce((entry, e) => entry.set(e['id'], {...entry.get(e['id'])||{}, ...e}), new Map()).values(); const result = [...iteratorMap]; console.log(result);
You can easily use lodash library and obtain the resutls
var result = _.chain(array)
.groupBy('id')
.map((val) => _.reduce(val, (result, value) => _.merge(result, value), {}))
.value()
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.