0

I am trying to get the id's from array of objects using the below code

const opaqueMaterialSecondaryIds = Object.values(library?.layers).reduce((acc, opaque) => {
    acc.push(...opaque.map(e => e.id));
    return acc;
  }, []);

and getting an error at opaque.map is not function and the object is looks like as below

enter image description here

i am not sure where i am doing wrong with the above code. Could any one please suggest any ideas on this, many thanks in advance.

3
  • can you post your json here Commented Dec 4, 2020 at 19:56
  • 2
    library?.layers?.map(item => item.id) Commented Dec 4, 2020 at 19:56
  • 1
    Why use reduce on layers rather than map? - It appears opaque is an object - hence, no map method. Commented Dec 4, 2020 at 19:57

2 Answers 2

1

map() is an Array method and doesn't exist in an object.

Each item in your library?.layers is an object, so opaque.map is not a function.

Side note 1: library?.layers is already an object, so you don't need to call Object.values() but can instead directly use library?.layers?.reduce().

Side note 2: if your purpose is to get the ids of all opaque objects, you can just do:

const opaqueMaterialSecondaryIds = library?.layers?.map(opaque => opaque.id);
Sign up to request clarification or add additional context in comments.

Comments

1

If your structure is what it looks like:

const layers = [
  {
    # other attributes,
    id: 'id-1',
    # other attributes,
  },
  {
    ...
  },
];

I think all you need is this:

const layerIds = layers.map((l) => l.id);
console.log(layerIds);
# Output: ['id-1', 'id-2']

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.