简体   繁体   中英

javascript combine array of object based on a single item object array in ES6

I have the following data

var data = [
  {username:'andy', entries:[{time_in:12, ..},{time_in:334,...}]},
  {username:'andy2', entries:[{time_in:'sr12', ..},{time_in:334,...}]}
]

What am looking forward to get is a final data with

var result = [
  {username:'andy', entry:12},
  {username:'andy', entry:334},
  {username:'andy2', entry:'sr12'},
  {username:'andy2', entry:334},
]

There are more properties per array object but for brevity i have included only username

So i have tried

data.forEach(item=>{
  item.entries.forEach(entry=>{
    //am stuck here
  })
})

You can use array#reduce with array#forEach . Iterate through each object and for each object iterate through entries array, add the new object in an accumulator.

 const data = [ {username: 'andy', entries: [{time_in: 12}, {time_in: 334}]}, {username: 'andy2', entries: [{time_in: 'sr12'}, {time_in: 334}]} ] const result = data.reduce((r, {username, entries}) => { entries.forEach(({time_in: entry}) => r.push({username, entry})) return r }, []) console.log(result) 

You could do something like this:

const final = [];
data.forEach(item =>
  item.entries.forEach(entry =>
    final.push({ username: item.username, entry: entry.time_in })
  )
);

I think map would do the trick:

var result = data.map((item) => {
    return {
        username: item.username,
        entries: item.entries.length, // Or whatever processing you want
        ...
    }
}

Here is the immutable version:

 const data=[ { username:'andy', entries:[{time_in:12},{time_in:334}] }, { username:'andy2', entries:[{time_in:'sr12'},{time_in:334}] } ]; const x = data.reduce((acc, {username, entries}) => acc.concat( entries.map(({time_in}) => ({ username, time_in })) ) , []); console.log(x); 

A possible solution:

const result = data.map(({username, entries}) =>
    entries.map(({time_in})=> ({username: username, entry: time_in}))
).reduce((acc, val) => [...acc, ...val], [])

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