Create dynamic object assignments within JavaScript objects

Check out this object sample, I want to iterate through and dynamically assign {"type": "object"} within each inner object.

Input:

var favoriteFruit = { "Amy": { "desc": "Amy's fav", "fruit": { "Name" : "Banana", "color" : "Red" } }, "Ben": { "desc": "Ben's fav", "fruit": { "Name" : "Apple", "color" : "Red" } }, "Carol": { "desc": "Carol's fav", "fruit": { "Name" : "Cherry", "color" : "Red" } }, "Olivia": { "desc": "Olivia fav", "fruit": { "Name" : "Orange", "color" : "Orange" } }, "Pualine": { "desc": "Pualine fav", "fruit": { "Name" : "Pear", "color" : "Green" } } };

Expected output:

var favoriteFruit = {
    "Amy": {
       "type": "object", 
       "desc": "Amy's fav",
         "fruit": {
            "Name" : "Banana",
            "color" : "Red"
         }
    },
    "Ben": {
        "type": "object", 
        "desc": "Ben's fav",
         "fruit": {
            "Name" : "Apple",
            "color" : "Red"
         }
    },
    "Carol": {
        "type": "object",
        "desc": "Carol's fav", 
         "fruit": {
            "Name" : "Cherry",
            "color" : "Red"
         }
    },
    "Olivia": {
        "type": "object",
         "desc": "Olivia fav", 
         "fruit": {
            "Name" : "Orange",
            "color" : "Orange"
         }
    },
    "Pualine": {
        "type": "object", 
        "desc": "Pualine fav",
         "fruit": {
            "Name" : "Pear",
            "color" : "Green"
         }
    }
};

Answer №1

Here is a modified version of the code snippet:

Take a look at the revised JSON string and the accompanying JavaScript code below:

var favoriteFruit = `{
    "Amy": {
       "desc": "Amy's fav",
        "fruit": {
            "Name" : "Banana",
            "color" : "Red"
         }
    },
    "Ben": {
       "desc": "Ben's fav",
       "fruit": {
            "Name" : "Apple",
            "color" : "Red"
         }
    },
    "Carol": {
        "desc": "Carol's fav",
        "fruit": {
            "Name" : "Cherry",
            "color" : "Red"
         }
    },
    "Olivia": {
        "desc": "Olivia fav",
        "fruit": {
            "Name" : "Orange",
            "color" : "Orange"
         }
    },
    "Pualine": {
        "desc": "Pualine fav",
        "fruit": {
            "Name" : "Pear",
            "color" : "Green"
         }
    }
}`;

// Converting the JSON string into an object
var obj = JSON.parse(favoriteFruit);

// Iterating through the object's properties
for(var prop in obj){
   // Adding a new property/value to each object
   obj[prop].type = "Object";
}

console.log(obj);

Answer №2

Start by iterating through the keys, which you can access using Object.keys(). From there, utilize Object.assign():

var favoriteFruit = {
  "Amy": {
    "desc": "Amy's fav",
    "fruit": {
      "Name": "Banana",
      "color": "Red"
    }
  },
  "Ben": {
    "desc": "Ben's fav",
    "fruit": {
      "Name": "Apple",
      "color": "Red"
    }
  },
  "Carol": {
    "desc": "Carol's fav",
    "fruit": {
      "Name": "Cherry",
      "color": "Red"
    }
  },
  "Olivia": {
    "desc": "Olivia fav",
    "fruit": {
      "Name": "Orange",
      "color": "Orange"
    }
  },
  "Pualine": {
    "desc": "Pualine fav",
    "fruit": {
      "Name": "Pear",
      "color": "Green"
    }
  }
}

Object.keys(favoriteFruit).forEach(function (key) {
  Object.assign(favoriteFruit[key], { type: 'object' })
})

console.log(favoriteFruit)

If it's important for you to have type as the first key when stringifying (although this is not necessarily guaranteed since keys are ultimately unordered), you can opt for this approach instead:

Object.keys(favoriteFruit).forEach(function (key) {
  favoriteFruit[key] = Object.assign({ type: 'object' }, favoriteFruit[key])
})

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

Exploring the functions keycode() and fromCharCode() in JavaScript

I recently wrote a jQuery script to display the key pressed by a user. Here is what I came up with: $(window).keydown(function(e){ $("div").text("Key:" + String.fromCharCode(e.keyCode).toLowerCase()); return false; }); Although this code accurately d ...

When a child component is updated, React does not automatically re-render

My goal is to pass the email from the SigninForm back to the App component and trigger a re-render when the email is updated. I attempted to follow the structure outlined in a previous question on Stack Overflow, but unfortunately, I couldn't get the ...

Express.js Router Middleware: Body Parsing with Hyphens in req.body

I have set up a URL endpoint to receive parsed emails from Mailgun through their API. The URL is an Expressjs Route to MongoDB using body parser middleware. While the HTTP post to MongoDB works fine for simple text keys like 'sender', I encounter ...

The Next.js error message reads: 'Issue with setting properties on undefined entity (specifically 'hook')'

This issue seems to occur either when the app is launched or when updating the Redux state. It may not show up consistently for every state update, but for some reason it persists throughout the entire app. What I have attempted so far: Removing node mod ...

Displaying data on a webpage using interpolation in HTML

I'm struggling to display user information on my HTML template. I can't seem to figure out what I'm doing wrong. Essentially, I want to retrieve values from the database and dynamically insert them into the main page for display. My issue li ...

Guide to deploying a Next JS App with Mongoose for MongoDB connectivity on Vercel

I am experiencing issues when trying to deploy my Next.js app on Vercel with a MongoDB connection. I have added environment variables on the Vercel site where we deploy the Next.js app. Is there anything wrong in the following file? next.config.js module. ...

Guide to sending various dates in the Check-in and Check-out sections on the website https://www.expedia.co.in/ using Python with Selenium

Currently developing a basic code to input and select arrival place, departure place, arrival date, and departure date on the Expedia website. Everything seems to be working fine except for the issue where the arrival date and departure date are displayin ...

The range filter is exclusive to the initial controller

My range filter (see code below) is only working on my first controller. I have added the same filter to other controllers in the app.js and HTML, but it's not functioning for some reason. I checked the console for errors, but there are none. Here i ...

What is the best way to trigger various sound files with a click?

I recently created a basic matching game that includes audio files for different cards. The code snippet below shows how I incorporated these audio files: cardList.map((cardItem) => { var card = document.createElement("li"); card.classList.add("card"); ...

Asserting types for promises with more than one possible return value

Struggling with type assertions when dealing with multiple promise return types? Check out this simplified code snippet: interface SimpleResponseType { key1: string }; interface SimpleResponseType2 { property1: string property2: number }; inter ...

Populate the div element with asterisks and prepare for printing

Is there a way to create a div filled with asterisks (*) without setting an exact width, but still keeping it on a single row like a border? I understand that using an asterisk image for the borders would be ideal, but due to constraints involving only ha ...

The initiation of jQuery animation through user interaction hinges on the completion of the preceding animation

In my project, I've designed a timeline that offers users the ability to zoom in and out by simply clicking on corresponding buttons. Since the timeline is too large to fit entirely on the screen, it is contained within a scrollable div. To ensure tha ...

Tips for aligning an image in the middle of a column within an ExtJS GridPanel

My goal is to center the icon horizontally within the "Data" column: Currently, I have applied textAlign: center to the column: Additionally, I am using CSS in the icon renderer function to horizontally center it: Despite these efforts, the icon remains ...

Creating a nested JSON structure by fetching data from a remote source

i'm looking to populate the json file located at through a get request. This json contains music from various churches in different cities, with data organized into multiple levels. I want to parse this data using jquery and utilize hidden div elemen ...

Click to remove with jQuery

My code currently wraps the label text in a span tag, but I want to remove the span tag when each span is clicked. For example, if I have test1 and test2 added, under Refined by:, clicking on test1 should remove that specific label or clicking on test2 sh ...

Is there a decrease in performance when interacting with variables in the method below?

Alright, I have a reference to a div stored in a variable, which I'll refer to as div_var. Now, when I want to apply some action to it, I have two options for referencing it: div_var.animate()...... $(div_var).animate()..... The first method is mor ...

The program encountered an error with com.fasterxml.jackson.databind.exc.MismatchedInputException because there was no content left to map when reaching the end

I am attempting to transform the following string: "{ \"contacts\": [{\"name\":\"1\",\"phone\":\"+123456\"}]}" into a custom object format: public class CustomObject{ private List<Contact> con ...

Tips on accessing a specific element that has been mapped in React?

TL;DR - I'm struggling to target and open a specific menu from a list generated using map() on an array without a reference. I've encountered an issue with my React.js code that I need assistance with to resolve. The main concept behind this lo ...

Set a class for the active menu item using jQuery based on the current window location

I have an HTML snippet here with a class called js-nav and a custom attribute named data-id. This data is crucial for determining the current sliding menu. <a class="nav-link js-nav" data-id="about" href="/#about">About</a> The approach I too ...

What is the best way to ensure that the function is referencing the class appropriately?

Typically when using this, it points to the class being referenced. However, in this scenario, this is set to dataChannel. How can I make this point back to VideoService? Thank you. export class VideoService { dataChannel:any; setupPeerConnectio ...