Add a distinct characteristic to each JSON object

If there is a JSON file with the following structure:

{
    "Person1": {
        "name": "Jon",
        "value1": 4,
        "value2": 2
    },
    "Person2": {
        "name": "Jane",
        "value1": 12,
        "value2": 3
    },
}

The goal is to add a new attribute to each object in the JSON file that is calculated as value1 divided by value2. For example, this new "value3" would be 2 for the first object and 4 for the second object. The desired output should resemble the following:

{
    "Person1": {
        "name": "Jon",
        "value1": 4,
        "value2": 2,
        "value3": 2
    },
    "Person2": {
        "name": "Jane",
        "value1": 12,
        "value2": 3,
        "value3": 4
    },
}

Automating this process is necessary since it needs to be done on a large scale. What would be the best approach to accomplish this?

Answer №1

utilize the Object.values method to extract values

obj={
  "Employee1": {
      "name": "Alice",
      "score1": 8,
      "score2": 3
  },
  "Employee2": {
      "name": "Bob",
      "score1": 15,
      "score2": 5
  },
}
Object.values(obj).forEach(person=>{
  person["result"]=person.score1/person.score2
})
console.log(obj)

Answer №2

To easily update all values, you can utilize the Array#forEach method on Object.keys.

const data = {
    "User1": {
        "name": "Sam",
        "score1": 7,
        "score2": 3
    },
    "User2": {
        "name": "Sara",
        "score1": 15,
        "score2": 5
    },
};
Object.keys(data).forEach(key=>data[key].averageScore = data[key].score1/data[key].score2);
console.log(data);

Answer №3

In my opinion, the outer brackets should be represented as [...] since it is an array.

Regarding your issue: one approach is to iterate through all elements - you can achieve this either by using arr.forEach() or a for-loop and assigning the value.

To assign the value, simply utilize

elem['value3'] = elem['value1'] / elem['value2']
, where elem refers to the current element.

It is important to ensure that both values are consistently available and that value2 is never 0. In the event that this would occur, it would be necessary to extend the code accordingly.

Answer №4

To prevent altering the original data, you have the option to utilize entries and fromEntries:

const data = {Person1:{name:"Jon",value1:4,value2:2},Person2:{name:"Jane",value1:12,value2:3}};

const result = Object.fromEntries(
  Object.entries(data)
    .map(([k, v]) => [k, { ...v, value3: v.value1 / v.value2 }])
);

console.log(result);

Answer №5

Example of using Object.entries() and a forEach loop to modify the original object

const obj = {Person1:{name:"Jon",value1:4,value2:2},Person2:{name:"Jane",value1:12,value2:3}};

Object.entries(obj).forEach(([key,{value1:v1,value2:v2}])  => obj[key].value3 = v1/v2)

console.log(obj)

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

Profile picture not found: JSON Error: Value is missing

I'm encountering an issue with my web service that is supposed to return a list of images (profile pictures), along with their names and ID numbers. Unfortunately, some members do not have profile pictures, so I am trying to add a default image from t ...

Numeric Input Box: Show gaps

I have numeric input boxes in my HTML/PHP/JS application where users will be entering numbers with 4 to 7 digits. However, I want the users to see spaces between every third digit for better readability. For instance, User types: 8000 Us ...

Analyzing JSON data and creating a tailor-made array

My Dilemma { "rowId": "1", "product_name": [ "Item A", "Item B", "Item C", "Item D", "Item E" ], "product_tag": [ "123456", "234567", "345678", "456789", "5678 ...

Modifying JavaScript Code in Inspect Element Editor

When I modify the HTML content using Chrome's Inspect Element editor, any changes made are immediately visible. However, when I make changes to the JavaScript code, the modifications do not take effect. For example, if I have a button that triggers a ...

Working with Node.js and JavaScript's Date object to retrieve the time prior to a certain number of hours

I am currently working on a script in node.js that is able to locate all files within a specific directory and retrieves their modified time: fs.stat(path, function(err, states){ console.log(states.mtime) }) After running the script, it ...

Sticky positioning with varying column widths

How can I create HTML and CSS columns that stick together without manually specifying the "left:" parameter every time? The current example in the fiddle achieves what I want, but requires manual setting of the "left:" value. Is there a way to make this m ...

Looking for guidance on integrating cookies with express session? Keep in mind that connect.sid is expected to be phased out

Within my app.js file, I have the following code snippet: app.use(session({secret: 'mySecret', resave: false, saveUninitialized: false})); While this setup functions correctly, it triggers a warning message: The cookie “connect.sid” will ...

Why is my JSON object being mistakenly interpreted as a string literal during iteration?

I'm facing a seemingly simple question but I can't seem to figure it out. Below is the jQuery code I am working with: $(function() { $.get(urlGetContainerNumbers, function(data) { console.log(data); for (var idx = 0; idx &l ...

The Issue of Double-Clicking on Table Cells in Internet Explorer 8

I implemented a JQuery function to add a double click event listener to a table, which triggers a modal popup when a cell is double-clicked. While this functionality works seamlessly in Firefox, there is an issue in IE8 where double-clicking a cell highli ...

Make sure to switch up the font color with each new use of the "append" function

Currently, on my page, I am using the append function to add a new line of text (".newText") every 5 seconds. This is my current implementation: var fontColors var randomColor $(function(){ fontColors = ['red','orange','yello ...

What is the best approach to retrieve a targeted JSON object list within a Flutter application?

Can anyone provide guidance on extracting only the "Image" data from a JSON object using Flutter? { "ID": 2, "Name": "krish", "info": [{ "Time": "07:30:00", &qu ...

What are the best techniques for showcasing rich text content in vue.js?

I'm working on a web application and attempting to showcase uploaded rich text content using vue.js. The content is generated by Action Text in the following format. <h1>text</h1><div>sample text<br><action-text-attachment ...

What is the best way to dynamically change className in React.js?

I am working on a Collection component where I need to change the classNames of both the Collection component and its first sibling component when a div is clicked. Even though I tried using UseState, I could only manage to change the className of the cur ...

Encountering a 405 Method Not Allowed error when using Laravel in conjunction with AngularJS

After successfully setting up Laravel Homestead and AngularJS, I am encountering an issue when trying to POST or GET data from the Laravel API using the Angular app. The errors displayed in the Firefox inspector Network tab include: 405 Method Not Allowed ...

Looking for a way to scroll images without relying on the marquee tag? Whether you prefer using JavaScript, jQuery,

<marquee> <div class="client"> <img src="images/c1.png"/> </div> <div class="client"> <img src="images/c2.png"/> </div> <div class="client"> ...

Tips for adding a string variable to a JQuery HTML element attribute

Hi there, I've been working on a JQuery code to append data to a div element and it's been successful so far. Here is the code: $('#conversation').append('<div id="receiver"><p><b>' + username + ':< ...

Include the script tags retrieved from an array

I'm exploring the idea of dynamically adding JavaScript to the DOM using an array and a loop. The goal is to load each script sequentially, starting with scripts[0], then scripts[1], and so on. var myScripts = [["external", "https://code.jquery.com/j ...

Troubles encountered during the installation of Visual Web Developer 2010?

Here is the situation I'm facing: After encountering some issues with PHP while working on an ASP.net project, I decided to reinstall everything. The installation of Apache, MySQL, and PHP went smoothly, but now I seem to be facing some problems. I ...

What is the best way to ensure there is only one instance of a React component visible at any given time?

In my current project with React, I am working on implementing a specific functionality. The challenge I am facing involves three components: ComponentA, ComponentB, and ComponentC. The twist is that ComponentC can be rendered as a child of either Compone ...

Guide to retrieving an array of objects from outside the function where it was initially declared

In my programming project, I have two classes - A and B. The class A contains a method called demo(), which creates an array of objects. The method uses a previously defined array1 of integers to retrieve a value 'v3', and then creates a new arra ...