1

I basically want to pull out the first object within an array and get it's name. The only challenge here is that I'm trying to destructure this within a parent object:

const exampleObject = {
  collection: [{
    name: "First Object",
  }, {
    name: "Second Object",
  }],
};

const {
  collection: [firstObject: {
    name
  }]
} = exampleObject;

console.log(firstObject);

Is sort of thing possible?

2

2 Answers 2

6

You need to switch it to:

{name: firstObject}
  |        |________ New variable name
  |    
  |_________________ Property name

const exampleObject = {collection: [{name: "First Object",}, {name: "Second Object",}],}

const { collection: [{ name: firstObject }] } = exampleObject

console.log(firstObject)

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

9 Comments

Oh okay so originally I was thinking I was extracting the array object by giving it the name of firstObject. Little did I know all I needed to do was something like this: [ { name }]. Correct?
@CarlEdwards if you don't want to rename it [{name}] is enoguh
@ Carl - Both of these are possible because destructuring syntax mirrors object and array literal syntax. In object literal syntax, {name: x} creates a property called name and gives it the value it gets from x. In destructuring syntax, {name: x} takes the value from name and puts it in x. That is, the things that are sources of values in literal syntax are targets of values in destructuring syntax. Onc eyou know that, since you're already familiar with literal syntax, destructuring becomes...well, I won't lie, it doesn't become second nature. But it gets easier.
Perfect. Thanks. Will accept this answer in a few. Maybe my memory is failing me but I thought that those above a certain karma count could accept immediately. Maybe it's something new. _(ツ)_/¯
@CarlEdwards - I think the delay applies to everyone. 15 minutes isn't long. :-)
|
1

If you need the name of first object you should write

const {
  collection: [{ name }]
} = exampleObject;

console.log(name);

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.