我需要将数组转换为对象,然后需要将对象属性值之一作为对象属性键名称移动:
[
{
"description": "red",
"type": "fruit",
"item": "apple"
},
{
"description": "yellow",
"type":"fruit",
"item": "banana"
}
]
到
{
"apple": {
"description": "red",
"type": "fruit"
},
"banana": {
"description": "yellow",
"type": "fruit"
}
}
使用Object.assign({}, ...arr)
将对象的名称填充到索引中,我需要更改该索引,谢谢!
答案 0 :(得分:3)
您可以使用Array#reduce
将数组折叠为对象。使用解构,您可以从对象中提取值,并以所需的格式为输出创建一个新对象。
const data = [
{
"description": "red",
"type": "fruit",
"item": "apple"
},
{
"description": "yellow",
"type":"fruit",
"item": "banana"
}
]
console.log(
data.reduce((accumulator, { item, description, type }) => ({
...accumulator,
[item]: { description, type }
}), {})
)
<script src="https://codepen.io/synthet1c/pen/KyQQmL.js"></script>
答案 1 :(得分:2)
您可以使用 Array.prototype.reduce
功能构建所需的输出。
var array = [ { "description": "red", "type": "fruit", "item": "apple" }, { "description": "yellow", "type":"fruit", "item": "banana" }],
result = array.reduce((a, {description, type, item}) => (Object.assign(a, {[item]: {description, type}})), {});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://codepen.io/synthet1c/pen/KyQQmL.js"></script>
无关:来自 @synthet1c
的Nice控制台插件答案 2 :(得分:0)
只需拨打reduce
即可完成。
const data = [{
"description": "red",
"type": "fruit",
"item": "apple"
},
{
"description": "yellow",
"type": "fruit",
"item": "banana"
}
]
const regrouped = data.reduce((acc, {
description,
type,
item
}) => {
acc[item] = {
description,
type
}
return acc
}, {});
console.log(regrouped)
答案 3 :(得分:0)
一种方法是在数组上使用forEach
并根据属性构建对象:
var arr = [{"description": "red", "type": "fruit", "item": "apple"},{"description":"yellow","type":"fruit","item": "banana"}]
obj = {};
arr.forEach((o) => {
obj[o.item] = o;
delete o.item;
});
console.log(obj)
&#13;
答案 4 :(得分:0)
其他答案很好地涵盖了vanilla JS解决方案,但是如果你可以使用lodash,你可以通过组合方法keyBy
,mapValues
和omit
来生成一个漂亮的单行:
const myArray = [{
"description": "red",
"type": "fruit",
"item": "apple"
}, {
"description": "yellow",
"type": "fruit",
"item": "banana"
}];
const result = _.mapValues(_.keyBy(myArray, o => o.item), o => _.omit(o, "item"));
console.log(result);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.5/lodash.min.js"></script>
答案 5 :(得分:0)
您可以使用reduce
let arr=[
{
"description": "red",
"type": "fruit",
"item": "apple"
},
{
"description": "yellow",
"type":"fruit",
"item": "banana"
}
]
const convert_to_object = (myarray) =>
myarray.reduce((o, i) => {
o[i.item] = {description:i.description,type:i.type}
return o
}, {})
const peopleObject = convert_to_object(arr)
console.log(peopleObject)