我需要帮助才能从本身嵌套到数组中的对象访问键值对的值(数组中有 2 个键值对的几个对象几个数组到一个对象中)。
例如,我只需要访问其中一个名字,例如 Max 或 Lucas...
我试图访问它但没有运气......任何帮助将不胜感激。
const nested = {
40: [
{ hello: "1", name: "Max" },
{ hello: "2", name: "Julie" },
{ hello: "3", name: "Mark" },
{ hello: "4", name: "Isabella" },
],
50: [
{ hello: "1", name: "William" },
{ hello: "2", name: "James" },
{ hello: "3", name: "Lucas" },
{ hello: "4", name: "John" },
],
};
// Here is what I tried but I didn't find any way to access a console.log that would return only a // single in the output.
const keysHello = Object.keys(nested);
console.log("keysHello", keysHello); // ['40', '50']
const values = Object.values(nested);
console.log("values", values); // [[{…}, {…}, {…}, {…}], [{…}, {…}, {…}, {…}])]
const keysValues = Object.entries(nested);
console.log("keysValues", keysValues); // [['40', [{…}, {…}, {…}, {…}]], ['50', [{…}, {…}, {…}, {…}]]
// The one below does not work
// const [, , {name}] = nested;
// console.log(`${Object.values[40]}`);
如果你知道你需要访问的键和索引,你可以只做
nested['40'][0].name
例如。
更通用:
const nested = {
40: [
{ hello: "1", name: "Max" },
{ hello: "2", name: "Julie" },
{ hello: "3", name: "Mark" },
{ hello: "4", name: "Isabella" },
],
50: [
{ hello: "1", name: "William" },
{ hello: "2", name: "James" },
{ hello: "3", name: "Lucas" },
{ hello: "4", name: "John" },
],
};
const key = '40';
const index = 0;
const { name } = nested[key][index];
看看你怎么不能做
nested.40
,因为数值不能与点符号一起使用。
你似乎对你在这里的工作感到困惑。你首先有一个对象,所以
const [, , {name}] = nested;
不会做任何事情。它是一个对象,而不是一个数组。
与
Object.values[40]
相同。有了那个,你就有了一组对象,所以在那个位置没有对象可以获取值。无论如何,您在那里错误地使用了Object.values
。你会做像Object.values(nested['40'][0])
.这样的事情
尝试:
console.log(nested['40']);
console.log(nested['40'][0]);
console.log(Object.values(nested['40'][0]));
另外值得一提的是,尽管您尝试使用数字,但这些数字用于数组,并且数字在这里被强制(更改)为字符串(在使用对象键时)。所以最好直接使用字符串以避免混淆。
const nested = {
'40': [
{ hello: "1", name: "Max" },
{ hello: "2", name: "Julie" },
{ hello: "3", name: "Mark" },
{ hello: "4", name: "Isabella" },
],
'50': [
{ hello: "1", name: "William" },
{ hello: "2", name: "James" },
{ hello: "3", name: "Lucas" },
{ hello: "4", name: "John" },
],
};