0

I have an object with these key-value pairs. This object comes from an API which I am calling :

APIName(obj).subscribe((res:any) => {
   console.log(Object.values(res.data));
})  



data = {
   0 : 1,
   1: 3,
   2: 7,
   3: 10
....so on
}

enter image description here

simply put it is an object of numbers and my desired output is (a simple array) :

data = [1,3,7,10]

I've tried Object.value and Object.key it still converts it into an object. Any help?

17
  • Second result in Google; stackoverflow.com/questions/38824349/… Commented Apr 15, 2022 at 10:45
  • 2
    data = Object.values(data) should work. Commented Apr 15, 2022 at 10:45
  • it's not working. I'll tell you what's exactly how it's not working. Commented Apr 15, 2022 at 10:47
  • @Shinichi - Object.values works just fine for this. What specific problem did you have with it? Commented Apr 15, 2022 at 10:48
  • 1
    @T.J.Crowder oh ok. I understood that now. Thanks a lot for your help. Commented Apr 15, 2022 at 11:09

1 Answer 1

-1

First of all if your data is not sorted by key. Then sort it. and iterate through object and push to array.

var data = {
   1: 1,
   0: 3,
   2: 7,
   3: 10
};
let sortedKeys = Object.keys(data).sort();
let arrayOfData = [];
// iterate method
sortedKeys.forEach((key) => {
  arrayOfData.push(data[key]);
});
console.log(arrayOfData);

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.