I'm writing a js code in which I need to update 1 JSON based on the condition from another JSON. Here are my code.
var a = [{
"a": "Not Started"
}, {
"b": "Not Started"
}, {
"c": "Not Started"
}, {
"d": "Not Started"
}, {
"e": "Not Started"
}];
var b = [{
"Id": 1,
"Stage": "c"
}];
a.forEach((obj) => {
for (const [key, value] of Object.entries(a)) {
a.value = 'complete'
if (key == b[0].Stage)
break
}
});
console.log(a);
Here is what I'm trying to do. Check what is the Stage
value in b
JSON variable. then moving to my a
JSON variable and looping over it. If Key
matches, the Stage
value, till the particular key, I want to update the value in a
variable to complete
, rest, just return as it is.
From the above snippet, the expected output is.
[{
"a": "complete"
}, {
"b": "complete"
}, {
"c": "complete"
}, {
"d": "Not Started"
}, {
"e": "Not Started"
}];
Since the Stage
value in b
stage is c
.
Please let me know how I can achieve this.
Thanks
if the keys of objects are alphabetical characters (assuming the example you have provided isn't a generalisation), you use take advantage of the ordering of character codes:
const a = [{
"a": "Not Started"
}, {
"b": "Not Started"
}, {
"c": "Not Started"
}, {
"d": "Not Started"
}, {
"e": "Not Started"
}];
const b = [{
"Id": 1,
"Stage": "c"
}];
for (obj of a) {
const key = Object.keys(obj)[0]
if (key.charCodeAt(0) <= b[0]["Stage"].charCodeAt(0)) {
obj[key] = "complete"
}
}
console.log(a)
if the alphabetical order isn't the case, you can follow the solution above
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With