1

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"
    }
  }
]
3
  • 2
    What you are expecting doesn't appear to be valid! A collection of objects inside an object without keys with that single object as the only entry in an array. Are you sure this is what you really want? Commented Apr 19, 2022 at 5:58
  • 1
    Your expected output object is not a valid object. First object inside array does not have key property. Objects inside that object must be having comma between them. Please make sure that you add correct output object in question so you will get accurate answers. Commented Apr 19, 2022 at 5:59
  • Let me edit the question again. Please wait Commented Apr 19, 2022 at 5:59

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.