Reputation: 1101
I have object in which if key does not exist set to null using javascript.
If the key doesnot exist in object obj
like ccy
does not exist cn
MY
and CA
, how to assign and set to null using javascript.
var obj=[{
"cn": "TH",
"lang": "thai",
"bank": "yes",
"ccy": "THB"
},{
"cn": "MY",
"lang": "malay",
},{
"cn": "CA",
"lang": "english",
"bank": "yes"
}]
render(){
obj.map(e=>
return html`
<h1>${e.cn}</h1>
<h5>${e.lang}</h5>
<h6>${e.ccy}</h6>
`
)
}
Upvotes: 3
Views: 147
Reputation: 773
var q = [...Object.keys(obj[0]),...Object.keys(obj[1]),...Object.keys(obj[2])]
for(let i=0;i<obj.length;i++){
for(let k=0;k<q.length;k++){
if(!(q[k] in obj[i])){
obj[i][q[k]] = null
}
}
}
console.log(obj)
Upvotes: 0
Reputation: 1089
There are multiple ways to check if a given key exists in an object.
if(!obj[0].hasOwnProperty('cn')) {
obj[o].cn = null
}
or
if(typeof obj[0].cn === 'undefined') {
obj[0].cn = null;
}
or
if(obj[0].cn === undefined) {
obj[0].cn = null;
}
The latter two are very similar in this case, typeof
is usually used when you want to check if a variable is defined and accessible in the code.
Now the real example is like so:
var missing = ['cn', 'ccy'];
for(var i = 0; i < obj.length; i++) {
for(var j = 0; j < missing.length; j++) {
if(!obj[i].hasOwnProperty(missing[j])) {
obj[i][missing[j]] = null;
}
}
}
Upvotes: 0
Reputation: 33726
You can use the operator in
to check if the key exists as follow:
The operator in
is the most secure way for avoiding wrong checks on falsy values.
{"ccy" in e ? e.ccy : null}
Upvotes: 2
Reputation: 193291
If you don't want to write default fallback values into template and want to keep template clean, you could also preprocess data and set missing values before rendering:
var obj = [{
"cn": "TH",
"lang": "thai",
"bank": "yes",
"ccy": "THB"
}, {
"cn": "MY",
"lang": "malay",
}, {
"lang": "english",
"bank": "yes"
}]
obj = obj.map(({
cn = null,
ccy = null,
...rest
}) => Object.assign(rest, { cn, ccy }))
console.log(obj)
Upvotes: 3
Reputation: 261
Any key not defined in a javascript object will be considered to be undefined so you could either check
(typeof obj.ccy === "undefined") ? null : obj.ccy;
(obj.ccy == undefined) ? null : obj.ccy;
If you are not familiar with ternary expressions. You could also write the above as this.
if(obj.ccy == undefined){
obj.ccy = null;
}
Upvotes: 0
Reputation: 44125
The easiest thing to do, as long as you can be sure e.ccy
won't be falsy (false
, undefined
, null
, 0
, ""
, or NaN
) is to use the logical OR operator ||
:
${e.ccy || null}
Upvotes: 4