简体   繁体   中英

Javascript copy nested array within object array

I have the following state object.

 list: [
      {
        "_id":"1","category":"Cat 1",
        "subcategory":[
          {"_id":"2","subcat":"Subcat 1"},
        ]
      },
      {"_id":"2","category":"Cat 2"},
    ],

I want to modify the values of _id:1. I make a copy of the object I need using:

let listCopy = list.filter(el => el._id == 1)

and then:

let subList = listCopy.subcategory.slice();

Why do I keep getting undefined for subList? What are some options for making a copy of the nested object?

The filter method returns an array and you expect an object. You can try listCopy[0].subcategory.slice(); if you just want one element.

The result is an array, so you need: listCopy[0]....

 var list = [ { "_id":"1", "category":"Cat 1", "subcategory":[ {"_id":"2","subcat":"Subcat 1"}, ] }, {"_id":"2", "category":"Cat 2" } ]; let listCopy = list.filter(el => el._id == 1) // Result is an array let subList = listCopy[0].subcategory.slice(); // <-- Need to use index console.log(subList); 

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