Object destructuring

hi guys, i’m trying to understand object destructuring

if i have

const people = {
id: 1,
firstName: ‘john’,
lastName: ‘Doe’,
age: 35

const { id, firstName, lastName, age } = person;
console.log(id, firstName,lastName,age);

i get the output:
// 1 John Doe 35

but what if i want

id: 1
firstName: John
lastName: Doe
age: 35

using only spread/rest operators?

const { id, firstName, lastName, age } = person;

Is the same as

const id = person.id;
const firstName = person.firstName;
const lastName = person.lastName
const age = person.age;

So, no, you can’t do that, destructing is for pulling values out. As it is, the thing you’re asking for is essentially what you have already: you can just do console.log(people) (or console.log(JSON.stringify(people)))

this is the exercise trace -.-

I’m not sure what you mean

the exercise say:

Use destructuring to print the list of property values ​​present in person:

result must be (string):

id: 1
firstName: John
lastName: Doe
age: 35

can you give a link to the exercise or copy and paste the instructions?

this is the blank exercise:

i need to replace the for loop with destructuring Edit fiddle - JSFiddle - Code Playground

Well, you can’t do that from just destructing – destructuring assigns a set of variables, and they have arbitrary names. You can’t get the name of a variable from a variable, that can’t possibly work.

You can get the values, and write them out, like

const myObject = {
  foo: 1,
  bar: 2,

const { foo, bar } = myObject;

  foo: ${foo}
  bar: ${bar}

Although that seems a little pointless.

You can’t really replace a loop with destructuring, they’re not equivalent things.

1 Like

Try this, might work
function printKeyVal(obj){

for(var [key, value] of Object.entries(obj)){

console.log(key +": "+value);



const person = {

id: 1,

firstName: ‘Mario’,

lastName: ‘Rossi’,

age: 25



I guess this is maybe what the OP’s task wants them to do? That’s the only thing that makes sense here afaics

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.