0

I am very new to development and have started working with arrays and objects. I want to modify the below structure.

[{
  "build": "Build 1",
  "date": "2019-08-16",
  "details": [{
    "type": "algo",
    "count": 1
  }, {
    "type": "Code",
    "count": 35
  }]
}, {
  "build": "Build 2",
  "date": "2019-08-08",
  "details": [{
    "type": "algo",
    "count": 2
  }, {
    "type": "Code",
    "count": 70
  }]
}]

This is the final structure that I want:

[{
  "build": "Build 1",
  "date": "2019-08-16",
  "type": "algo",
  "count": 1
}, {
  "build": "Build 1",
  "date": "2019-08-16",
  "type": "code",
  "count": 35
}, {
  "build": "Build 2",
  "date": "2019-08-08",
  "type": "algo",
  "count": 2
}, {
  "build": "Build 2",
  "date": "2019-08-08",
  "type": "code",
  "count": 70
}]

Is there any way to do this in Javascript or jQuery? Any help will be appreciated. Thanks in advance.

2
  • 2
    Welcome to stackoverflow. This is not a coding service website. Show us, what you have done so far in a Minimal, Complete, and Verifiable example and you'll get help Commented Aug 16, 2019 at 9:23
  • Just FYI, the data structure you have is an array of objects. It has nothing to do with JSON, so I edited that out of your question Commented Aug 16, 2019 at 9:31

2 Answers 2

5

You could take (upcoming) Array#flatMap and a destructuring for the details and a rest in object destructuring.

Then map both objects.

var data = [{ build: "Build 1", date: "2019-08-16", details: [{ type: "algo", count: 1 }, { type: "Code", count: 35 }] }, { build: "Build 2", date: "2019-08-08", details: [{ type: "algo", count: 2 }, { type: "Code", count: 70 }] }],
    result = data.flatMap(({ details, ...o }) => details.map(p => ({ ...o, ...p })));

console.log(result);

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

1 Comment

+1 for being quicker than me, and giving a more elegant implementation :) It's worth noting that flatMap() is unsupported in IE and Edge, though
0

Approach without flatMap

// data is your JSON

return [].concat(...data.map(({details, ...object}) => details.map(detail => 
  ({
      ...detail,
      ...object
  }))
))

3 Comments

Your avoidance of flatMap(), presumably in an attempt to make this work cross-browser, is made redundant by your use of the spread operator, as that won't work in IE or Edge in this scenario, either.
Agree, but spread operators are more supported than flatMap. Used to caniuse.com for this statistics
spread operators are more supported than flatMap That's true, but in this case neither will work in any version of IE, and as you're using the spread within an object, it won't work in Edge.

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.