2

I have the following structure :

[
   {
     "key": "Asset Type",
     "values": ["Appliances", "Electronics"]
    }, 
    {
      "key": "Asset Availability",
      "values": ["In Stock"]
    }
]

I need to convert it to :

{
  "Asset Type": ["appliances", "electronics"],
  "Asset Availability": ["in stock"]
}

How can I do that?

Kimaya
  • 1,210
  • 4
  • 14
  • 33

3 Answers3

7

Here is one approach using Object.fromEntries and Array.prototype.map (to transform the array into 2d-array since that's what the Object.fromEntries expect)

const items = [{
    "key": "Asset Type",
    "values": ["Appliances", "Electronics"]
  },
  {
    "key": "Asset Availability",
    "values": ["In Stock"]
  }
]

console.log(
  Object.fromEntries(items.map(({
    key,
    values
  }) => [key, values]))
)
Tibebes. M
  • 6,940
  • 5
  • 15
  • 36
0

Here is one of the simplest solution I found

const items = [
    {
     "key": "Asset Type",
     "values": ["Appliances", "Electronics"]
    }, 
    {
      "key": "Asset Availability",
      "values": ["In Stock"]
    }
]
let output = items.map((obj)=>{
    let result = {};
    result[obj.key] = obj.values;
    return result;
    });
console.log(output);
Sanky
  • 11
  • 5
0

Another simple solution is using Array.prototype.reduce() method

const array = [
  {
    key: 'Asset Type',
    values: ['Appliances', 'Electronics']
  },
  {
    key: 'Asset Availability',
    values: ['In Stock']
  }
]

console.log(
  array.reduce((acc, rec) => {
    acc = { ...acc, [rec.key]: rec.values }
    return acc
  }, {})
)
  • 1
    `acc = { ...acc, [rec.key]: rec.values }` - why introduce this complicated destructuring, which will cause the object to be reconstructed every time? `acc[rec.key] = rec.values` has the same effect and is shorter and more readable – Klaycon Sep 21 '20 at 19:07
  • I agree with you. – Alexey Eremin Sep 21 '20 at 19:13