Steve Gaita
Steve Gaita

Reputation: 181

Remove object Key of an javascript object

I have a Javascript object like this:

{
    "xx2b": {
        "county": "Baringo",
        "town": "Kabarnet",
        "saccoRegistration": "BO2/08/009",
        "saccoName": "Baringo2"
    },
    "QQDa": {
        "saccoRegistration": "Ba/09/009",
        "town": "Mogotio",
        "county": "Baringo",
        "saccoName": "Baringo1"
    }
}

I would like to convert it to remove the key for each object and push it to be a property within the objects like this:

{
    {
        "id": "xx2b",
        "county": "Baringo",
        "town": "Kabarnet",
        "saccoRegistration": "BO2/08/009",
        "saccoName": "Baringo2"
    },
    {  
        "id": "QQDa",
        "saccoRegistration": "Ba/09/009",
        "town": "Mogotio",
        "county": "Baringo",
        "saccoName": "Baringo1"
    }
}

Upvotes: 1

Views: 42

Answers (1)

Majed Badawi
Majed Badawi

Reputation: 28434

You need to store the result in an array as follows:

const data = {
  "xx2b": { "county": "Baringo", "town": "Kabarnet", "saccoRegistration": "BO2/08/009", "saccoName": "Baringo2" },
  "QQDa": { "saccoRegistration": "Ba/09/009", "town": "Mogotio", "county": "Baringo", "saccoName": "Baringo1" }
};

const res = Object.entries(data).map(([id, props]) => ({ ...props, id }));

console.log(res);

Upvotes: 2

Related Questions