如何将对象转换为对象数组

时间:2018-04-03 11:01:40

标签: javascript

我有以下对象:

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

我需要将其转换为以下结构:

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

5 个答案:

答案 0 :(得分:7)

使用Object.entriesarray.prototype.map和一些destructuring



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

console.log(res);




答案 1 :(得分: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));




答案 2 :(得分:2)

我最喜欢的方法是:

  1. 在对象的每个键上调用map函数。
  2. 创建一个新对象,其属性“name”设置为键,值为相应值
  3. 请注意,此方法中的密钥必须是唯一的(无论如何都应该如此):

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

答案 3 :(得分:0)

尝试这样==>

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

答案 4 :(得分:0)

你可以尝试这样的东西或使用地图功能有很多方法

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