Javascript Lodash复杂键值替换
我使用的是lodash/3;,我想从输入JSON生成以下输出 任何关于如何实现这一点的意见都将是非常好的 输入:Javascript Lodash复杂键值替换,javascript,lodash,Javascript,Lodash,我使用的是lodash/3;,我想从输入JSON生成以下输出 任何关于如何实现这一点的意见都将是非常好的 输入: { "hex": "#EFDECD", "name": "Almond", "rgb": "(239, 222, 205)" }, { "hex": "#CD9575", "name": "Antique Brass", "rgb": "(205, 149, 117)" }, 期望输出: { Almond: '#EFDECD',
{
"hex": "#EFDECD",
"name": "Almond",
"rgb": "(239, 222, 205)"
},
{
"hex": "#CD9575",
"name": "Antique Brass",
"rgb": "(205, 149, 117)"
},
期望输出:
{
Almond: '#EFDECD',
Antique Brass: '#CD9575',
...
};
感谢您的时间您可以使用纯Javascript来实现这一点(
Array.prototype.reduce
):
const集合=[{
十六进制:'#EFDECD',
名称:“杏仁”,
rgb:“(2392222205)”,
},
{
十六进制:“#CD9575”,
名称:“古董黄铜”,
rgb:“(205、149、117)”,
},
]
const sorted=collection.reduce((结果,el)=>{
结果[el.name]=el.hex
返回结果
}, {})
console.log(排序)
您可以使用普通Javascript来实现这一点(Array.prototype.reduce
):
const集合=[{
十六进制:'#EFDECD',
名称:“杏仁”,
rgb:“(2392222205)”,
},
{
十六进制:“#CD9575”,
名称:“古董黄铜”,
rgb:“(205、149、117)”,
},
]
const sorted=collection.reduce((结果,el)=>{
结果[el.name]=el.hex
返回结果
}, {})
console.log(已排序)
使用可以使用数组.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;
}, {});
使用可以使用
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;
}, {});
如果您真的想使用lodash,那么reduce功能也确实可以使用:
const集合=[{
十六进制:'#EFDECD',
名称:“杏仁”,
rgb:“(2392222205)”,
},
{
十六进制:“#CD9575”,
名称:“古董黄铜”,
rgb:“(205、149、117)”,
},
]
const sorted=\减少(集合,(结果,el)=>{
结果[el.name]=el.hex
返回结果
}, {})
console.log(已排序)
如果您真的想使用lodash,那么reduce功能也确实在那里可用:
const集合=[{
十六进制:'#EFDECD',
名称:“杏仁”,
rgb:“(2392222205)”,
},
{
十六进制:“#CD9575”,
名称:“古董黄铜”,
rgb:“(205、149、117)”,
},
]
const sorted=\减少(集合,(结果,el)=>{
结果[el.name]=el.hex
返回结果
}, {})
console.log(已排序)