0

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
  })
})
1
  • You want to merge the objects into a single one? Am I right? Commented Jun 25, 2018 at 12:01

5 Answers 5

3

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

0

You could do something like this:

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

Comments

0

A possible solution:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.