我正在从Firebase数据库中检索书籍列表,其中每个“书籍”都是一个对象。
书籍的有效载荷是这样的一个整体对象:
{
key1: {
"title": "A Good Book"
"author": "A Person"
},
key2: {
"title": "Another Good Book"
"author": "Another person"
}
...and so on
}
我需要将该整体对象更改为对象数组,以便可以映射每个对象并提取所需的值。
我需要的预期数组:
[
{
"title": "A Good Book"
"author": "A Person"
},
{
"title": "Another Good Book"
"author": "Another person"
}
]
我尝试使用Object.entries(myObject)
和Object.values(myObject)
,但这只会返回有关对象的乱码。
我从堆栈溢出尝试了其他答案,例如:
var array = Object.entries(data).map(([phrase, date]) => ({phrase,date}));
但这不起作用。
最初,我认为这应该是直接且常见的问题,但是经过几天的堆栈溢出和google梳理后,我没有遇到类似的问题和解决方案。
答案 0 :(得分:0)
像这样的对象中必须有一些键(我对其进行了编辑):
let data = {
{
"Harry Potter": {
"BookInfo": {
"Pages": 500,
"Author": "JK Rowling"
},
"SaleInfo": "For Sale"
},
"A Clockwork Orange": {
"BookInfo": {
"Pages": 200,
"Author": "Anthony Burgess"
},
"SaleInfo": "For Sale"
}
}
...and so on
}
如果是这样,则可以将Object.valus()
用作:
const books = {
"Harry Potter": {
"BookInfo": {
"Pages": 500,
"Author": "JK Rowling"
},
"SaleInfo": "For Sale"
},
"A Clockwork Orange": {
"BookInfo": {
"Pages": 200,
"Author": "Anthony Burgess"
},
"SaleInfo": "For Sale"
}
...
}
const booksMapped = Object.keys(books).map(bookName => {
return {
bookName,
...books[bookName]
}
})
console.log(booksMapped)
/*
[
{
"bookName": "Harry Potter",
"BookInfo": {
"Pages": 500,
"Author": "JK Rowling"
},
"SaleInfo": "For Sale"
},
{
"bookName": "A Clockwork Orange",
"BookInfo": {
"Pages": 200,
"Author": "Anthony Burgess"
},
"SaleInfo": "For Sale"
}
]
*/
基本上Object.keys()
将为您提供一个数组,其中包含每个给定的键对象,然后您可以在其上链接任何数组方法
例如:
地图
减少
forEach
过滤器
找到
等
let person {
name: "John Doe",
age: 18
}
Object.keys(person) // => ["name", "age"]
Object.values(person) // => ["John Doe", 18]
答案 1 :(得分:0)
const input = {
"Harry Potter": {
BookInfo: { Pages: 500, Author: "JK Rowling" },
SaleInfo: "For Sale",
},
"A Clockwork Orange": {
BookInfo: { Pages: 200, Author: "Anthony Burgess" },
SaleInfo: "For Sale",
}
};
const output = Object.entries(input).map(([title, value ]) => ({
title,
author: value.BookInfo.Author
}))
console.log(output)
答案 2 :(得分:0)
最优雅的解决方案是使用flatMap():
const sorce = {
key1: {
"title": "A Good Book",
"author": "A Person"
},
key2: {
"title": "Another Good Book",
"author": "Another person"
}
};
const result = Object.keys(sorce).flatMap(key => sorce[key]);
console.log(result);
结果: [ {标题:“一本好书”,作者:“一个人”},
{title:“另一本好书”,作者:“另一个人”} ]
P.S。在这种情况下,我们可以使用map来获得相同的结果:
const result = Object.keys(sorce).map(key => sorce[key]);