简体   繁体   中英

how to make nested array objects in javascript in a key value pair format

array data=[
{
"id":1,
"name":"john",
"income":22000,
"expenses":15000
},
{
"id":2,
"name":"kiran",
"income":27000,
"expenses":13000
},
{
"id":1,
"name":"john",
"income":35000,
"expenses":24000
}
]

i want to make a new array set in following format which is in a key value pair. ie result set. can you please explain the best method. ? how to achive using foreach.?

tried using foreach method by looping each element. but cant get the desired output format

var result= [ {
      "name": "john",
      "series": [
        {
          "name": "income",
          "value": 22000
        },
        {
          "name": "expenses",
          "value": 15000
        },
       
      ]
    },
{
      "name": "kiran",
      "series": [
        {
          "name": "income",
          "value": 27000
        },
        {
          "name": "expenses",
          "value": 13000
        },
       
      ]
    }]
// Your array
const result = [
  {
    name: "john",
    series: [
      {
        name: "income",
        value: 22000,
      },
      {
        name: "expenses",
        value: 15000,
      },
    ],
  },
  {
    name: "kiran",
    series: [
      {
        name: "income",
        value: 27000,
      },
      {
        name: "expenses",
        value: 13000,
      },
    ],
  },
];

// What is .map function?
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

// Output

// map return a new function.
// it's a loop method but more equipped
result.map((item, index) => {
  const seriesKeyValues = {};
  // forEach is too, it's a loop method.
  // but not have a return value,
  // just loops and give you item on each loop
  item.series.forEach(serie => {
    //seriesKeyValues is a object.
    // different between seriesKeyValues.serie.name
    // it's a bracket notation
    // look this documentation
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#computed_property_names
    seriesKeyValues[serie.name] = serie.value;
  });

  // return new Object
  // ... is 'spread syntax' basically combine objects
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#spread_properties
  // spread syntax is a new way.
  // old way is https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

  return {
    id: index,
    name: item.name,
    ...seriesKeyValues,
  };
});

I hope it will help:). if you don't understand any lines of code, i can explain

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM