0

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?

3
  • 1
    Just FYI filter is not making copies of your objects. Not related to your issue but I'm dropping this anyway. Commented Mar 4, 2018 at 23:12
  • It's because listCopy is an array, and your object will be found in listCopy[0] Commented Mar 4, 2018 at 23:12
  • 2
    Given you're using ES2015, you might have used Array.prototype.find Commented Mar 4, 2018 at 23:12

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Ah! I see. My oversight
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.