Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Convert object to array object

Try to convert the following object (which was getting from an API response) to an array object.

const oldObj = {
    Georgia : {
        notes: "lorem ipsum",
        lat: "32.1656",
        long: "82.9001"
    },
    Alabama : {
        notes: "lorem ipsum",
        lat: "32.3182",
        long: "86.9023"
    }
}

My expected like bellow:

const desireArray = [
    {
        name: "Georgia",
        notes: "lorem ipsum",
        lat: "32.1656",
        long: "82.9001"
    },
    {
        name: "Alabama",
        notes: "lorem ipsum",
        lat: "32.3182",
        long: "86.9023"
    }
];

Try to do with forEach but, I think it's not the way, seemed returned me the error.

oldObj.forEach((el, i) => {
    console.log(el);
});

TypeError: oldObj.forEach is not a function

Any help?

like image 442
Daniel Smith Avatar asked May 16 '26 11:05

Daniel Smith


1 Answers

forEach is method for array, meanwhile your oldObj is object

First you have to transform it to array, here we could do is transforming object to array of key-values pairs

And using with map could make code shorter

const oldObj = {
  Georgia: {
    notes: "lorem ipsum",
    lat: "32.1656",
    long: "82.9001",
  },
  Alabama: {
    notes: "lorem ipsum",
    lat: "32.3182",
    long: "86.9023",
  },
}

const res = Object.entries(oldObj).map(([name, obj]) => ({ name, ...obj }))

console.log(res)

References

Object.entries()

like image 128
hgb123 Avatar answered May 19 '26 01:05

hgb123



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!