JS - 如何将所有键转换为其值(来自对象)

时间:2017-03-07 18:01:04

标签: javascript node.js object type-conversion

我有类似的东西(我从API获取它,所以我无法改变它):

obj.

我希望将所有“价格”,“重量”和“颜色”键转换为其值,如下所示:

{ one: [ { price: ['$10'], weight: ['1000'], color: ['red'] } ],
  two: [ { price: ['$20'], weight: ['2000'], color: ['green'] } ],
  three: [ { price: ['$30'], weight: ['3000'], color: ['blue'] } ] }

有没有简单的方法可以做到这一点?

编辑:示例已修复
Edit2:通缉结果已修复

1 个答案:

答案 0 :(得分:2)

您可以映射使用键并将所需属性映射到内部数组。

var object = { one: [ { price: ['$10'], weight: ['1000'], color: ['red'] } ], two: [ { price: ['$20'], weight: ['2000'], color: ['green'] } ], three: [ { price: ['$30'], weight: ['3000'], color: ['blue'] } ] };

Object.keys(object).forEach(function (k) {
    object[k] = [ 'price', 'weight', 'color'].map(function (p) {
        return object[k][0][p][0];
    });
});

console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }