const mydata = {
message: 'Hello Vues!',
language: {
en: {show: false, displayname: "English"},
ja: {show: true, displayname: "Japanese"},
zh: {show: false, displayname: "Chinese"},
}
}
I would like to loop through the 'langauge' object, target it's children, and change all their property "show" into false.
The goal is as follow:
const mydata = {
message: 'Hello Vues!',
language: {
en: {show: false, displayname: "English"},
ja: {show: false, displayname: "Japanese"},
zh: {show: false, displayname: "Chinese"},
}
}
I am looking at Object.entries
and I can sort of extract the 3 keys (which is en, ja and zh).
for (const [key, value] of Object.entries(mydata.language)) {
console.log(key); //----> gets names of keys
console.log(key.displayname);//----> undefined
}
However I cant seemed to reference them, loop through it's children and change all 3 records of "show" into false.
Am I looking at the wrong command here?
CodePudding user response:
You can just loop over the value of mydata.language
with the help of forEach
and make show
as false
as:
Object.values(mydata.language).forEach((o) => o.show = false);
const mydata = {
message: 'Hello Vues!',
language: {
en: { show: false, displayname: 'English' },
ja: { show: true, displayname: 'Japanese' },
zh: { show: false, displayname: 'Chinese' },
},
};
Object.values(mydata.language).forEach((o) => o.show = false);
console.log(mydata);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
CodePudding user response:
you can use
mydata.language[key].show = false;
Or
value.show = false;
CodePudding user response:
You can achieve this via the Object.keys
method which will return an array of a given object's own enumerable property names, followed by the forEach
method which will execute a provided function once for each array element. In that function you will set the show
value to false.
const mydata = {
message: 'Hello Vues!',
language: {
en: {show: false, displayname: "English"},
ja: {show: true, displayname: "Japanese"},
zh: {show: false, displayname: "Chinese"},
}
}
Object.keys(mydata.language).forEach(x => mydata.language[x].show = false);
console.log(mydata);
CodePudding user response:
You can use Object.values
to get the inner objects -- you don't really need the keys then:
const mydata = {
message: 'Hello Vues!',
language: {
en: {show: false, displayname: "English"},
ja: {show: false, displayname: "Japanese"},
zh: {show: false, displayname: "Chinese"},
}
}
for (let obj of Object.values(mydata.language)) {
obj.show = false;
}
console.log(mydata.language);