Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to build a json array with custom elements with javascript

I’m using JavaScript, I have an array:

[
  { "id": "0", "name": "test1", "brand": "brand1" },
  { "id": "0", "name": "test1", "brand": "brand2" },
  { "id": "0", "name": "test1", "brand": "brand3" },
  { "id": "2", "name": "test2", "brand": "brand100" },
  { "id": "2", "name": "test2", "brand": "brand101" },
  { "id": "2", "name": "test2", "brand": "brand102" },
  { "id": "2", "name": "test2", "brand": "brand103" },
  { "id": "2", "name": "test2", "brand": "brand104" }
]

I’m using JavaScript to have something like this:

[
  {
    "id": "0",
    "name": "test1",
    "brand": [
      "brand1",
      "brand2",
      "brand3"
    ]
  },
  {
    "id": "2",
    "name": "test2",
    "brand": [
      "brand100",
      "brand101",
      "brand102",
      "brand103",
      "brand104"
    ]
  }
]

The script is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let result=[]
for (var i = 0; i < brands.length; i++) {
let id =brands[i].id
    if(i==0){

        result.push(

          {
          "id": brands[i].id,
          "name": brands[i].name, 
           } )
 else{
        result.push(
           "id": brands[i].id,
          "name": brands[i].name )
    }
}

But it seems that it doesn’t work…?

>Solution :

You could take an object for the obj3ects with same id and get all values of it as result;

const
    data = [{ id: "0", name: "test1", brand: "brand1" }, { id: "0", name: "test1", brand: "brand2" }, { id: "0", name: "test1", brand: "brand3" }, { id: "2", name: "test2", brand: "brand100" }, { id: "2", name: "test2", brand: "brand101" }, { id: "2", name: "test2", brand: "brand102" }, { id: "2", name: "test2", brand: "brand103" }, { id: "2", name: "test2", brand: "brand104" }],
    result = Object.values(data.reduce((r, { id, name, brand }) => (
        (r[id] ??= { id, name, brand: [] }).brand.push(brand),
        r
    ), {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading