3 回答
TA贡献1833条经验 获得超4个赞
看起来像整数的键没有什么特别之处。在 JavaScript 中,属性名总是字符串,它们看起来像大整数这一事实无关紧要。就像对待任何其他对象一样对待它。
您可以使用Object.keys()
获取属性名称数组、Object.values()
获取属性值数组以及Object.entries()
获取名称和值的二维数组。
Object.entries(data).forEach(([key, value]) => console.log(`${key} added on ${value.added}`);
TA贡献1847条经验 获得超11个赞
您正在尝试从一个对象访问 .map() ,您要做的是将您的对象变成一个数组:
const data = {
342227492064425: {
added: "2020-10-04T23:02:28.030432",
listed: "2020-10-04T23:02:28.030432",
subscribed: "2020-10-04T23:02:28.030432",
},
342731155590705: {
added: "2020-10-04T23:02:28.030432",
listed: "2020-10-04T23:02:28.030432",
subscribed: "2020-10-04T23:02:28.030432",
},
};
//create the array which will hold all the values of the object
const data_array = [];
//loop through the object keys and store their values in data_array
for (let key of Object.keys(data)) {
data_array.push(data[key]);
}
//now data_array[0].subscribed is accessible
console.log(data_array[0].subscribed);
//map() is also accessible
data_array.map((item) => {
/* logic */
});
TA贡献1864条经验 获得超6个赞
data.length
您不能在对象中使用,应该用于计算字符串和/或数组长度中的字符数
一个 Number,表示数组对象中元素的个数
参考:JavaScript 数组长度属性
如果您需要使用,我对您有一个建议,data.length
所以基本上将您的对象推送到一个新数组。
有很多方法可以做到这一点,例如
var data = [];
var objects = {"342227492064425":
{"added":"2020-10-04T23:02:28.030432",
"listed":"2020-10-04T23:02:28.030432",
"subscribed":"2020-10-04T23:02:28.030432"},
"342731155590705":
{"added":"2020-10-04T23:02:28.030432",
"listed":"2020-10-04T23:02:28.030432",
"subscribed":"2020-10-04T23:02:28.030432"}
}
// Convert Objects to Array via forEach function and Push method
Object.entries(objects).forEach((key, value) => data.push(key));
数组值:
console.log(data);
输出:
/*
["342227492064425", {added: "2020-10-04T23:02:28.030432", listed: "2020-10-04T23:02:28.030432", subscribed: "2020-10-04T23:02:28.030432"}],
["342731155590705", {added: "2020-10-04T23:02:28.030432", listed: "2020-10-04T23:02:28.030432", subscribed: "2020-10-04T23:02:28.030432"}]
*/
第一个 ID 值
console.log(data[0][0])
第二个 ID 值
console.log(data[1][0])
访问第一个对象值
console.log(data[0][1].added)
console.log(data[0][1].listed)
console.log(data[0][1].subscribed)
访问第二个对象值
console.log(data[1][1].added)
console.log(data[1][1].listed)
console.log(data[1][1].subscribed)
现在,您可以使用data.length输出是:(2)
添加回答
举报