简体   繁体   English

从 JSON 中的嵌套数组访问值

[英]Accessing a value from a nested array in JSON

const data = fs.readFileSync('./movies.JSON');
data.toString();
var obj = JSON.parse(data);
console.log(Object.values(obj.moviesList));

This is my js file.这是我的 js 文件。 This prints all keys and pairs of my JSON file.这将打印我的 JSON 文件的所有密钥和对。 I am trying to access the nested array in the JSON file.我正在尝试访问 JSON 文件中的嵌套数组。 I have tried console.log(Object.values(obj.moviesList.actors==="206'));我试过console.log(Object.values(obj.moviesList.actors==="206'));

And a bunch of other variations.还有一堆其他的变化。

    "moviesList":[
    {
        "movieId": 4192148,
        "title": "Highly Functional",
        "actors": [
            3188187,
            3306943,
            132257,
            47265
        ]
    },

here is a small snippet of my JSON file containing nested arrays.这是我的 JSON 文件的一小段,其中包含嵌套的 arrays。

I want to start out by printing out all movie Id's that have an actor whose id is 206.我想首先打印出所有具有 id 为 206 的演员的电影 ID。

If you are scanning a nested array, here's one way to about that using includes to check the actors array.如果您正在扫描嵌套数组,这是使用includes检查演员数组的一种方法。

 const moviesList = [{ "movieId": 4192148, "title": "Highly Functional", "actors": [ 3188187, 3306943, 132257, 47265 ] }, { "movieId": 11111, "title": "Highly Functional2", "actors": [ 3188187, 3306943, 206, 47265 ] }, { "movieId": 11112, "title": "Highly Functional3", "actors": [ 3188187, 3306943, 206, 47265 ] } ]; let matches = []; for (const movie of moviesList) { const { actors, movieId } = movie; if (actors.includes(206)) { matches.push(movieId); } } console.log(matches); // Another format matches = moviesList.filter(({ actors }) => actors.includes(206)).map(({ movieId }) => movieId) console.log(matches);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM