构造对象数组,默认值

时间:2018-04-19 12:54:51

标签: javascript destructuring

如果值为undefined,我想设置对象属性的默认值。

当从tags数组中导出name属性时,我想将属性重命名为colour,并设置默认值(如果未定义)。

我该怎么做?

我目前使用以下代码获取名称未定义

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

这给了我colour is undefined

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

示例数据:

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":[]}

1 个答案:

答案 0 :(得分:1)

这有帮助吗?

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

如果对象中不存在t:

var {x,y,z,t:[{name:colour = "none"}]=[{name:"none"}]} = {x:3,y:2,z:1};
console.log(colour);//"none"
PS:它似乎在你的对象中&#34; t&#34;可能被定义为空数组,在这种情况下:

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

PS2:以下是您提供的样本数据的概念证明:

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"

虽然我应该说你发布的原始示例和你提供的样本数据没有相同的结构。在您的原始帖子中,其他属性(如描述等)位于标记键之外,而在示例中,您提供的所有内容都位于标记数组中。