Bomber
Bomber

Reputation: 10967

Destructure array of objects, default value

I would like to set the default value of an object property if the value is undefined.

When destructing from the tags array, the name property, I would like to rename the property to colour, and set the default value if its undefined.

How can I do that?

I currently get name not defined with the code below:

const {
  description,
  categories,
  id,
  title,
>>  tags: [{ name: colour= 'none' }], <<
  organizer: [{ organizer: organiser }],
  venue: { venue }
} = event;

This gives me colour is undefined

            const {
                description,
                categories,
                id,
                title,
                tags: [{name:colour = "none"}={name:"none"}]=[{name:"none"}],
                organizer: [{ organizer: organiser }],
                venue: { venue }
            } = event;

Sample data:

const sample = {"tags":[{"name":"red","slug":"red","term_group":0,"term_taxonomy_id":125,
"taxonomy":"post_tag","description":"","parent":0,"count":1,"filter":"raw","id":125,"urls"}]}

or empty const sample = {"tags":[]}

Upvotes: 0

Views: 84

Answers (1)

ibrahim tanyalcin
ibrahim tanyalcin

Reputation: 6501

Does this help?

var {x,y,z,t:[{name:colour = "none"}]=[{name:"none"}]} = {x:3,y:2,z:1,t:[{name:"gray"}]};
console.log(colour);//"gray"

If t does not exist in the object:

var {x,y,z,t:[{name:colour = "none"}]=[{name:"none"}]} = {x:3,y:2,z:1};
console.log(colour);//"none"

PS: It seems to be in your object "t" might be defined as an empty array, in that case:

 var {x,y,z,t:[{name:colour = "none"}={name:"none"}]=[{name:"none"}]} = {x:3,y:2,z:1,t:[]};
console.log(colour);//"none"

PS2: Here is proof of concept from the sample data you provided:

var {x,y,z,tags:[{name:colour = "none"}={name:"none"}]=[{name:"none"}]} = {x:3,y:2,z:1,"tags":[{"name":"red","slug":"red","term_group":0,"term_taxonomy_id":125,
"taxonomy":"post_tag","description":"","parent":0,"count":1,"filter":"raw","id":125,"urls":"some"}]};
console.log(colour);//"red"

Although I should say the original example you post and the sample data you provide do not have identical structure. In your original post other properties like description etc are outside the tags key whereas in the sample you provide everything is inside the tags array.

Upvotes: 1

Related Questions