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

时间:2019-05-22 02:47:47

标签: javascript json

我需要编写一个函数来转换这样的对象:

const foodList = {fruit: {apples: true, pears: false, berries: true}, dairy: {milk: true, cheese: false}, vegetables: {}}
console.log(foodList)

对此:

const result = {fruit: ['apples', 'berries'], dairy: ['milk']}
console.log(result)

我正在尝试将嵌套值转换为食物键等于true的数组。

2 个答案:

答案 0 :(得分:3)

您可以使用Object.entries将对象转换为数组。使用reduce循环和汇总数组。使用Object.keysfilter获取具有真实值的密钥。

const foodList = {"fruit":{"apples":true,"pears":false,"berries":true},"dairy":{"milk":true,"cheese":false},"vegetables":{}}

const result = Object.entries(foodList).reduce((c, [k, v]) => {
  let t = Object.keys(v);
  if (t.length) c[k] = t.filter(o => v[o]);
  return c;
}, {});

console.log(result);

答案 1 :(得分:2)

获得所需输出的另一种方法是使用两个嵌套的for循环在生成结果对象的同时遍历外键和内键。这样,如果类别中的所有元素都具有property值,则还可以避免在结果object上生成false

const foodList = {
  fruit: {apples: true, pears: false, berries: true},
  dairy: {milk: true, cheese: false},
  vegetables: {},
  food: {hamburger: false, spaghetti: false}
};

let res = {};

for (const category in foodList)
{
    for (const item in foodList[category])
    {
        if (foodList[category][item])
        {
            res[category] = res[category] || [];
            res[category].push(item);
        }
    }
}

console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}