将对象嵌套到数组中,并嵌套到对象中

Nested Objects into Arrays into an Object

提问人:Donut 提问时间:4/17/2023 更新时间:4/17/2023 访问量:50

问:

我需要帮助才能从本身嵌套在数组中的对象(数组内有 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]}`);
JavaScript 数组 对象 嵌套 键值

评论

0赞 pilchard 4/17/2023
这回答了你的问题吗?如何访问和处理嵌套对象、数组或 JSON?

答:

1赞 moonwave99 4/17/2023 #1

例如,如果您知道需要访问的密钥和索引,则可以这样做。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

1赞 anon 4/17/2023 #2

你似乎对你在这里工作的内容感到困惑。你先有一个对象,所以不会做任何事情。它是一个对象,而不是一个数组。const [, , {name}] = nested;

与 .有了这个,你就有一个对象数组,所以在该位置没有对象可以获取值。无论如何,你在那里使用不正确。你会做这样的事情.Object.values[40]Object.valuesObject.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" },
    ],
};