Lodash复杂的键值替换

时间:2017-08-23 11:02:58

标签: javascript lodash

我正在使用lodash / _,并且我想从输入JSON生成以下输出。

关于如何实现这一目标的任何意见都会很棒。

输入:

{
    "hex": "#EFDECD",
    "name": "Almond",
    "rgb": "(239, 222, 205)"
},
{
    "hex": "#CD9575",
    "name": "Antique Brass",
    "rgb": "(205, 149, 117)"
},

期望的输出:

{
  Almond: '#EFDECD',
  Antique Brass: '#CD9575',
  ...
};

感谢您的时间

3 个答案:

答案 0 :(得分:2)

您可以使用普通的Javascript来实现(Array.prototype.reduce):



const collection = [{
    hex: '#EFDECD',
    name: 'Almond',
    rgb: '(239, 222, 205)',
  },
  {
    hex: '#CD9575',
    name: 'Antique Brass',
    rgb: '(205, 149, 117)',
  },
]

const sorted = collection.reduce((result, el) => {
  result[el.name] = el.hex
  return result
}, {})
console.log(sorted)




答案 1 :(得分:2)

使用可以使用Array.prototype.reduce方法:

let data = [{
  "hex": "#EFDECD",
  "name": "Almond",
  "rgb": "(239, 222, 205)"
},
{
  "hex": "#CD9575",
  "name": "Antique Brass",
  "rgb": "(205, 149, 117)"
}];

let newData = data.reduce((result, elem) => {
    result[elem.name] = elem.hex
    return result;
}, {});

答案 2 :(得分:1)

只是因为你真的想要lodash,还可以使用reduce功能:



const collection = [{
    hex: '#EFDECD',
    name: 'Almond',
    rgb: '(239, 222, 205)',
  },
  {
    hex: '#CD9575',
    name: 'Antique Brass',
    rgb: '(205, 149, 117)',
  },
]

const sorted = _.reduce(collection, (result, el) => {
    result[el.name] = el.hex
    return result
}, {})

console.log(sorted)

<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
&#13;
&#13;
&#13;