skip to Main Content

I have an array of objects, the objects are the same but with different values. What I need is to generate a new object but concatenating the values of the same property.

This is the array:

interface Test {
  group: string,
  model: any
}
let dataObj: Test[] = [
  {
    "group":"car",
    "model":{
      "test":"test1",
      "data":"data1"
    }
  },
  {
    "group":"car",
    "model":{
      "test":"test2",
      "data":"data2"
    }
  }
]

This is what I do:

let result = {
  visualize: {}
}
dataObj.forEach((item: Test) => {

  const { group, model } = item

  result.visualize[group] = {
    model
  }

})

This is what I get:

{"visualize":{"car":{"model":{"test":"test2","data":"data2"}}}}

This is what I need:

{"visualize":{"car":{"model":{"test":"test1,test2","data":"data1,data2"}}}}

2

Answers


  1. You can use Array.reduce() to iterate over the dataObj array and accumulate the result in the result object.

    let result = {
      visualize: {}
    }
    
    dataObj.reduce((acc, item) => {
      const { group, model } = item;
      if (acc[group]) {
        Object.keys(model).forEach(key => {
          acc[group].model[key] += `,${model[key]}`;
        });
      } else {
        acc[group] = { model };
      }
      return acc;
    }, result.visualize);
    

    And then the output should be :

    {
      "visualize": {
        "car": {
          "model": {
            "test": "test1,test2",
            "data": "data1,data2"
          }
        }
      }
    }
    
    Login or Signup to reply.
  2. You need to add to the same group.

    const
        dataObj = [{ group: "car", model: { test: "test1", data: "data1" } }, { group: "car", model: { test: "test2", data: "data2" } }],
        result = { visualize: {} };
    
    dataObj.forEach(({ group, model }) => {
        const temp = result.visualize[group] ??= {};
        Object.entries(model).forEach(([k, v]) => {
            temp[k] ??= '';
            temp[k] += (temp[k] && ',') + v;
        });
    });
    
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search