我的数组如下:
Array [
Object {
"color": "Brown",
"time": "18:32",
},
Object {
"color": "Red",
"time": "18:33",
},
]
但是如何将Object更改为名称?
我这样推它
const itemLogs = [];
childSnapshot.forEach((csh) => {
let childKeys = csh.key;
itemLogs.push({
color: csh.val().color,
time: csh.val().time
});
});
this.setState({childData: itemLogs});
更新:
这就是我想要的方式:
10-05-2019 [
14:27 {
"color": "Brown",
"time": "14:27",
},
14:23 {
"color": "Red",
"time": "14:23",
},
],
11-06-2019 [
like above but other data
]
我希望这是一个更好的示例。
答案 0 :(得分:1)
调试器可以像这样可视化您的数据:
Array [
Object {
"color": "Brown",
"time": "18:32",
},
Object {
"color": "Red",
"time": "18:33",
},
]
但实际上看起来像这样:
[
{
"color": "Brown",
"time": "18:32",
},
{
"color": "Red",
"time": "18:33",
},
]
您可以使用以下方法向您的对象添加name
属性:
itemLogs.push({
color: csh.val().color,
time: csh.val().timem,
name: 'YOUR_NAME_GOES_HERE'
});
然后您的数据将如下所示:
[
{
"color": "Brown",
"time": "18:32",
"name": "YOUR_FIRST_NAME",
},
{
"color": "Red",
"time": "18:33",
"name": "YOUR_SECOND_NAME",
},
]
更新的解决方案:
const itemLogs = {}; //create an object
var arr = []; // create a temporary array
var tmp = {}; //create a temporary object
tmp["14:27"] = {
"color": "Brown",
"time": "14:27",
};
arr.push(tmp); // add object to array
var tmp2 = {}; //create another tmp object
tmp2["14:23"] = {
"color": "Red",
"time": "14:23",
};
arr.push(tmp2); // add object to array
itemLogs["10-05-2019"] = arr; // add the array to itemLogs with new key
console.log(itemLogs);
答案 1 :(得分:0)
感谢蒂姆
let userId = firebase.auth().currentUser.uid;
firebase.database().ref('table/' + userId).on('value', (snapshot) => {
const itemLogs = {};
const tmp = {};
snapshot.forEach((childSnapshot) => {
childSnapshot.forEach((csh) => {
tmp[csh.key] = {
color: csh.val().color,
time: csh.val().time
};
});
itemLogs[childSnapshot.key] = tmp;
console.log(itemLogs);
});
});
现在看起来像这样:
Object {
"11-5-2019": Object {
"18:32": Object {
"color": "Brown",
"time": "18:32",
},
"18:33": Object {
"color": "Red",
"time": "18:33",
},
},
}