Home > Back-end >  Javascript - convert object of object into array and use the key inside array
Javascript - convert object of object into array and use the key inside array

Time:04-19

I have an object of objects which I have converted into an array, I now want to use the key of each item into the array as a separate value.

The code I have tried.

let data = {
  99: {
    "avg": [1,2],
    "min": [],
    "max": []
  },
  100: {
    "avg": [50,10],
    "min": [],
    "max": []
  },
  120: {
    "avg": [42,8],
    "min": [],
    "max": []
  },
}

var arr = Object.keys(data).map(function (key) {
  return { [key]: data[key] };
});

arr.forEach(element => {
  element.sensor = Object.keys(element);
});

console.log(arr);

And the output is

[
  {
    "99": {
      "avg": [
        1,
        2
      ],
      "min": [],
      "max": []
    },
    "sensor": [
      "99"
    ]
  },
  {
    "100": {
      "avg": [
        50,
        10
      ],
      "min": [],
      "max": []
    },
    "sensor": [
      "100"
    ]
  },
  {
    "120": {
      "avg": [
        42,
        8
      ],
      "min": [],
      "max": []
    },
    "sensor": [
      "120"
    ]
  }
]

But I want the expected output to be like this.

     [
  {
    "99": {
      "avg": [
        1,
        2
      ],
      "min": [],
      "max": [],
      "sensor": "99"
    }
  },
  {
    "100": {
      "avg": [
        50,
        10
      ],
      "min": [],
      "max": [],
      "sensor": "100"
    }
  },
  {
    "120": {
      "avg": [
        42,
        8
      ],
      "min": [],
      "max": [],
      "sensor": "120"
    }
  }
]

CodePudding user response:

You can use the ... spread operator to append the sensor value when converting the object to array itself

var arr = Object.keys(data).map(function (key) {
  return { 
    [key]: { ...data[key], sensor: key } 
  };
});

let data = {
  99: {
    "avg": [1,2],
    "min": [],
    "max": []
  },
  100: {
    "avg": [50,10],
    "min": [],
    "max": []
  },
  120: {
    "avg": [42,8],
    "min": [],
    "max": []
  },
}

var arr = Object.keys(data).map(function (key) {
  return { [key]: { ...data[key], sensor: key } };
});

 

console.log(arr);

  • Related