我需要将对象数组转换为JavaScript中的对象对象。 书籍的ID应该是数组中每个对象的ID。
我拥有的数组:
[{
"author" : "cccc",
"catid" : 22,
"id" : 25,
"logo" : "logo",
"name" : "Book c",
"size" : 84777
}, {
"author" : "ddd",
"catid" : 22,
"id" : 26,
"logo" : "logo",
"name" : "Book d",
"size" : 105139
}]
我需要的对象
{
"25":{
"author" : "bbbb",
"catid" : 22,
"logo" : "logo",
"name" : "Book b",
"size" : 73386
},
"26":{
"author" : "cccc",
"catid" : 22,
"logo" : "logo",
"name" : "Book c",
"size" : 84777
}}
答案 0 :(得分:3)
您可以使用reduce:
const arr = [{
"author": "aaaa",
"catid": 22,
"id": 23,
"name": "Book a",
"size": 56658
}, {
"author": "bbbb",
"catid": 22,
"id": 24,
"logo": "logo",
"name": "Book b",
"size": 73386
}, {
"author": "cccc",
"catid": 22,
"id": 25,
"logo": "logo",
"name": "Book c",
"size": 84777
}, {
"author": "ddd",
"catid": 22,
"id": 26,
"logo": "logo",
"name": "Book d",
"size": 105139
}]
const obj = arr.reduce((acc, {id, ...obj}) => {
acc[id] = obj
return acc
}, {})
console.log(obj)
Reduce将遍历数组中的每个对象,并且内部代码会将对象通过id附加到acc
累加器中,然后将其作为对象返回。
答案 1 :(得分:0)
上面给出的方法的问题在于它仅限于将要使用新对象密钥的对象。让我们对此进行抽象,以便在所有情况下都可以重复使用该功能!
如上面查询中所述,您希望将名为BookArray的JSON数组转换为名为BookObject的JSON对象,如下所示。
const bookArray = [{
"author" : "cccc",
"catid" : 22,
"id" : 25,
"logo" : "logo",
"name" : "Book c",
"size" : 84777
}, {
"author" : "ddd",
"catid" : 22,
"id" : 26,
"logo" : "logo",
"name" : "Book d",
"size" : 105139
}]
Your resulting bookObject after processing should look like this.
const bookObject = {
"25":{
"author" : "bbbb",
"catid" : 22,
"logo" : "logo",
"name" : "Book b",
"size" : 73386
},
"26":{
"author" : "cccc",
"catid" : 22,
"logo" : "logo",
"name" : "Book c",
"size" : 84777
}}
const arrayToObject = (array, keyField) =>
array.reduce((obj, item) => {
obj[item[keyField]] = item
return obj
}, {})
const bookObject = arrayToObject(bookArray, "id")
console.log(bookObject[idToSelect])
上面的代码现在接受一个keyField,它使我们能够使用此函数转换任何对象数组。不只是那些具有字段ID的人。这对于代码的可重用性很重要。