2

I have the following object :

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

I need to convert it to the following structure :

[
   {
     "name": "Asset Type",
     "values": ["Appliances", "Electronics"]
    }, 
    {
      "name": "Asset Availability",
      "values": ["In Stock"]
    }
]
Karim
  • 8,454
  • 3
  • 25
  • 33
  • Note that you can’t make any assumptions about the order of the resulting array elements. – Sebastian Simon Apr 03 '18 at 11:30
  • 1
    @SebastianSimon If you want to be guaranteed by the spec, you can, but only if you use the right methods (like `Reflect.ownKeys`). If you just want the result to be *dependable*, you can use any of the object iteration methods - although the spec doesn't guarantee it, environments use the same algorithm anyway, luckily. (array indicies, followed by insertion order strings, followed by insertion order symbols) – CertainPerformance Sep 25 '19 at 08:43

5 Answers5

9

Use Object.entries, array.prototype.map and some destructuring:

var categories = {
  "Asset Type": ["appliances", "electronics"],
  "Asset Availability": ["in stock"]
 };
 
var res = Object.entries(categories).map(([name, values]) => ({name, values}));

console.log(res);
Faly
  • 13,291
  • 2
  • 19
  • 37
2

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

const toArray = obj => 
  Object.keys(obj).reduce((acc, key) => [...acc, {name: key, values: obj[key]}], [])

console.log(toArray(categories));
Karim
  • 8,454
  • 3
  • 25
  • 33
2

The approach i like the most is to:

  1. Call the map function on each key of the object.
  2. Create a new object with the property "name" set to the key and the value to the corresponding value

Please note that the key has to be unique in this approach (which it should be anyways):

var categories = {
  "Asset Type": ["appliances", "electronics"],
  "Asset Availability": ["in stock"]
 };

var res = Object.keys(categories).map(key => ({
      name: key,
      values: categories[key]
    });
);

console.log(res);
Larce
  • 841
  • 8
  • 17
0

Try like this ==>

var obj = {
    "categories":
         {
          "Asset Type": ["appliances", "electronics"],
          "Asset Availability": ["in stock"]
         },
};


var categories = [];
for(let p in obj.categories) {

    categories.push({
        name: p,
        values : obj.categories[p]
    });
}

console.log(categories);
Rajib Chy
  • 800
  • 10
  • 22
0

you can try something like this or use map function there is a lot of ways

let obj = {
    "categories":
        {
            "Asset Type": ["appliances", "electronics"],
            "Asset Availability": ["in stock"]
        }

}
let categories=[];
Object.keys(obj.categories).forEach(key=>{
    categories.push({"name":key,"value":obj.categories[key]});
});
console.log(categories);
Abdelrahman Hussien
  • 505
  • 2
  • 4
  • 17