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?

0

3 Answers 3

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]))
)

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

Comments

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);

Comments

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
  }, {})
)

2 Comments

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
I agree with you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.