Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to update a json value in a loop

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

like image 562
user3872094 Avatar asked Mar 01 '23 15:03

user3872094


1 Answers

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

like image 142
charmful0x Avatar answered Mar 05 '23 17:03

charmful0x