undefinedfix
Sign in

How to gracefully judge whether an object and an attribute in the object exist (JS)

Jean edited in Tue, 04 Oct 2022

like this , You need to get the padding value of the incoming parameter , But it's not sure if elestyle was passed in , It is more uncertain whether other properties in elestyle are passed in , At present, ternary expression is used to judge , But it's still a bit cumbersome ...

data: {
    show: true,
    //可能传入的参数
    eleStyle: {
        //以下某一参数均有可能不传
        width: 100,
        height: 100,
        padding: 20,
    }
}
let padding = eleStyle && eleStyle.padding ? eleStyle.padding : 10
//当eleStyle.padding为0时, 所得到的padding值仍为默认, 所以可能应该是下面这种:
let padding = eleStyle && eleStyle.padding !== undefined ? eleStyle.padding : 10

If the required parameters are taken from deeper objects , That is also very bloated , So please ask if there is any good way to solve this problem ...

5 Replies
mathisfun
commented on Tue, 04 Oct 2022
let padding = 'eleStyle.padding'.split('.').reduce((res,key)=>{return res != null ? res[key] : null},data)
padding = padding != null ? padding : 10;
Schmango
commented on Tue, 04 Oct 2022

30 seconds of code is a very elegant way to write, you can refer to it. The internal implementation of other practices may be different, but the concept is very similar.

const get = (from, ...selectors) =>
  [...selectors].map(s =>
    s
      .replace(/\[([^\[\]]*)\]/g, '.$1.')
      .split('.')
      .filter(t => t !== '')
      .reduce((prev, cur) => prev && prev[cur], from)
  );
oindk
commented on Tue, 04 Oct 2022

JS is really not a good solution. Ts3.7 provides a solution to deal with your needs

interface EleStyle{
    width?:Number,
    height?:Number,
    padding?:Number
}
interface Data {
    show:Boolean,
    eleStyle?:EleStyle
}

let data:Data = {
    show:true,
    eleStyle:{
        width: 100,
        height: 100
    }
}

console.log(data.eleStyle?.padding);
user132972
commented on Wed, 05 Oct 2022

After looking at the document, I don't know how reduce works here

jet_black82
commented on Wed, 05 Oct 2022

lodash _ .get

_.get(eleStyle, 'padding', 10)
lock This question has been locked and the reply function has been disabled.