'Convert JSON to array without key

I have a query to return a column from the database which gets return the following result:

[
{
    "tenantName": "H&M"
},
{
    "tenantName": "McDonalds"
}
]

However, I want to use the result to create an array that only has the names: ["H&M", "McDonalds"]



Solution 1:[1]

you can use map together with Object.values and flat

  • map(i => Object.values(i)) - it creates array of arrays //[['HM'], ['McDons']]
  • flat will create one level array

const input = [
{
    "tenantName": "H&M"
},
{
    "tenantName": "McDonalds"
}
];

const result = input.map(i => Object.values(i)).flat()
console.log(result)

if you know that one item(object) of array always will have key tenantName then you can use only map

    const input = [
    {
        "tenantName": "H&M"
    },
    {
        "tenantName": "McDonalds"
    }
    ];

    const result = input.map(i => i.tenantName)
    console.log(result)

Solution 2:[2]

You can use map

const tenantArray = [ { "tenantName": "H&M" }, { "tenantName": "McDonalds" }].map(tenant => tenant.tenantName)

Solution 3:[3]

Array.prototype.map() works well for this.

var data = [
      {
        tenantName: "H&M",
      },
      {
        tenantName: "McDonalds",
      },
    ];


    function filterJSON(json){
    return json.map(i => i.tenantName);
    }

    console.log(filterJSON(data));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Damian Busz
Solution 3 David