Struggling to modify a JSON value within a loop

I am currently developing a JavaScript code that involves updating one JSON based on conditions from another JSON. Below is the code I have written.

const a = [{
  "a": "Not Started"
}, {
  "b": "Not Started"
}, {
  "c": "Not Started"
}, {
  "d": "Not Started"
}, {
  "e": "Not Started"
}];

const 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);

The goal here is to check the value of the Stage key in the b JSON variable and then iterate through the a JSON variable. If there is a match between the keys, update the corresponding value in the a variable to complete, leaving everything else unchanged.

Based on the above code snippet, the expected output should be:

[{
  "a": "complete"
}, {
  "b": "complete"
}, {
  "c": "complete"
}, {
  "d": "Not Started"
}, {
  "e": "Not Started"
}];

This is because the Stage value in the b JSON is set to c.

If you have any suggestions on how to achieve this, please let me know.

Thank you!

Answer №1

When the keys of objects are arranged in alphabetical characters (assuming the specific scenario you provided isn't a broad generalization), you can utilize the ordering of character codes:

const items = [{
  "a": "Not Started"
}, {
  "b": "Not Started"
}, {
  "c": "Not Started"
}, {
  "d": "Not Started"
}, {
  "e": "Not Started"
}];

const reference = [{
  "Id": 1,
  "Stage": "c"
}];


for (element of items) {
  const key = Object.keys(element)[0]
  if (key.charCodeAt(0) <= reference[0]["Stage"].charCodeAt(0)) {
    element[key] = "complete"
  }
}

console.log(items)

If the order is different, you can implement the solution outlined above.

Answer №2

var tasks = [{
  "task1": "Not Started"
}, {
  "task2": "Not Started"
}, {
  "task3": "Not Started"
}, {
  "task4": "Not Started"
}, {
  "task5": "Not Started"
}];

var stages = [{
  "Id": 1,
  "Stage": "task3"
}];

var index = tasks.findIndex(task => Object.keys(task)[0] === stages[0].Stage);

for (var i = 0; i <= index; i++){
    const key = Object.keys(tasks[i])[0];
    tasks[i][key] = "complete";
}

console.log(tasks);

Answer №3

Here is a more versatile solution for scenarios where b may consist of multiple elements:

var x = [{
  "a": "Not Started"
}, {
  "b": "Not Started"
}, {
  "c": "Not Started"
}, {
  "d": "Not Started"
}, {
  "e": "Not Started"
}];

var y = [{
  "Id": 1,
  "Stage": "b"
}, {
  "Id": 2,
  "Stage": "c"
}];

const currentStage = y.sort((a,b) => b["Id"] - a["Id"])[0]["Stage"]

x = x.map(element => {
  const [[character, state]] = Object.entries(element)
  const inCurrentStage = character.charCodeAt(0) <= currentStage.charCodeAt(0)
  const currentState = inCurrentStage ? "completed" : state
  return Object.fromEntries([[character, currentState]])
})

console.log(x)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript For/in loop malfunctioning - Issue with undefined object property bug

Currently, I am tackling a basic For/in loop exercise as part of a course curriculum I am enrolled in. The exercise involves working with a simple object containing 3 properties and creating a function that takes two parameters - the object name and the it ...

Having trouble getting the Javascript dropdown script to work on a Wordpress page?

Hello all, I've been experimenting with creating a simple dropdown menu for my Wordpress website. The idea is that when a user clicks on a specific text, a dropdown menu with various links will appear. I followed the guidance from W3 Schools, but unfo ...

What is the best way to retrieve data from a JSON object?

Can the status variable be used as a JSON object? What is the method to access the values of action_success and newIndex within the status object? Server: [HttpPost] public ActionResult UploadFiles() { // save file.. return Json(new { action_suc ...

The mongoimport jsonArray feature functions smoothly in a 64-bit build, but encounters an exception in a 32-bit environment

I have MongoDB standalone servers running in two different systems - one with Windows 8.1 Pro 64 Bit (MongoDB 2.6 64 Bit) and the other with Windows 7 Pro 32 Bit (MongoDB 2.6 32 Bit). Although mongoimport csv functions correctly on both systems, I encount ...

What is the process for adding images from CSS (backgrounds, etc.) to the build folder with webpack?

Trying out the file loader for processing images and adding them to my build folder. Images within HTML files successfully show up in the build, but the ones from styles do not. I've divided my webpack configuration into two separate files and use t ...

Capture element in Javascript with screenshot functionality

I've been trying to save an image on my local website, but most of the code examples I find are for C# and Java, which I am struggling to convert to JavaScript. Many of the examples I come across use libraries like Point and IO that are not available ...

Jasmine - effectively mimicking an object that utilizes a constructor

Currently, I am attempting to simulate the native WebSocket in a jasmine test for Angular. I have successfully spied on the constructor and `send` function, but I am struggling to figure out how to fake a call of `onmessage`. The WebSocket has been extrac ...

Guide to linking NodeJs with an Atlas mongodb Cluster

I am currently in the process of setting up a new application that utilizes an Atlas Database with node. Unfortunately, I keep encountering an error message that reads: "MongoError: MongoClient must be connected before calling MongoClient.prototype.db". ...

JavaScript tabs function malfunctioning upon page load

I attempted to implement tabs on my website using this example: http://www.w3schools.com/howto/howto_js_tabs.asp Although everything is functioning correctly, the default tab isn't opening as expected. The tab opens, but the header color does not get ...

Querying JSON data in SQL Server

I am dealing with a table that contains a column filled with JSON data. [ {"Name":"Territory","Value":"1000000002"},{"Name":"Village","Value":"Bahaibalpur"}, {"Name":"Activity Date","Value":"2016-6-15 5:30:0"}, {"Name":"Start Time","Value":"16:37"}, {"Nam ...

Having difficulty selecting a nested ul with CSS, I'm currently exploring different options

For the website I am working on, I have a cms system that is responsible for rendering menus. My current task involves selecting the children of the parent menu items, and here is how the code is being generated: <div class="menu"> <ul> ...

"Keeping your HTML content up-to-date with AngularJS dynamic updates

I've noticed that when I upload changes to my AngularJS HTML partial files, there is a caching issue where the old data is displayed. It takes a few refresh actions before the changes become visible. Is there a way to make these changes appear immedi ...

When aot is enabled, ngClass and ngIf condition may not compile successfully

I am encountering an issue with a div using ngClass and ngIf conditions: <div [ngClass]="{ 'active': nbActive === 1 }" > <!-- some stuff --> </div> There is also a similar div using a ngIf condition: <div *ngIf="nbActi ...

JavaScript and PHP/HTML template engine technology

I've recently discovered the jQuery template engine and am intrigued by its potential. It seems to be very efficient for ajax calls, as the data exchange is minimized. However, when I initially load my application using only PHP and HTML to display ...

Different language implementations of AES ECB mode yield varying outputs

I have encountered an issue while attempting to transfer an AES encrypted string from a python script to a nodejs script using ECB mode. The relevant code snippets are as follows: Firstly, I utilize pycryptodome to encrypt a string with AES: from Crypto.C ...

Using PHP to extract information from a JSON file

After researching various articles and tutorials, I've managed to piece together the code below. However, as a beginner in PHP, JSON, and Javascript, I am seeking guidance. The task at hand is to update a div with the ID "playerName" every 10 seconds ...

What is the best way to implement a delay for ajax requests triggered by onkeyup events, and then restart the delay countdown each

Is there a way to add a delay for ajax requests triggered by onkeyup and reset the delay if onkeyup is triggered again? For instance, consider this code: When a user enters data into id="fname" triggering an onkeyup event, a loading span id="loading" wil ...

Is there any benefit to making the SVG elements width and height 100%?

The Angular Material documentation app features an SVG Viewer that is able to scale the SVG content to fit the container using the following function: inlineSvgContent(template) { this.elementRef.nativeElement.innerHTML = template; if (this.sca ...

Eliminate unneeded null and empty object data attributes within Vue.js

When sending object data to an API, I have multiple states but not all of them are required every time. Therefore, I would like to remove any properties from the object that are null or empty strings. How can I achieve this? export default { methods: { ...

Incorporating Content-Disposition headers to enable the file to be both downloaded and opened

I'm having trouble allowing users to both view and download files on a web page. I've tried setting headers and using JavaScript, but can't seem to get it right. My goal is to have an HTML page with two links for each file - one to open in ...