Home > front end >  how to build a json array with custom elements with javascript
how to build a json array with custom elements with javascript

Time:02-12

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:

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

CodePudding user response:

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

CodePudding user response:

You have some syntax problems in your code (You have missed brackets). Here is a fixed one:

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
        });
    }
}
  • Related