简体   繁体   中英

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. This prints all keys and pairs of my JSON file. I am trying to access the nested array in the JSON file. I have tried 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.

I want to start out by printing out all movie Id's that have an actor whose id is 206.

If you are scanning a nested array, here's one way to about that using includes to check the actors array.

 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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