Having difficulty including a new key-value pair to a JSON object while using another JSON object

Looking to merge key value pairs from one JSON object into another.

I've searched through various stackoverflow threads for solutions, but haven't found one that works for my specific scenario.

const primaryObject = {
  name: "John Doe",
  age: 30,
  city: "New York"
}

var secondaryObject = {
  details: {}
};

for (var key in primaryObject) {
  if (primaryObject.hasOwnProperty(key)) {
    secondaryObject.details[key] = primaryObject[key];
  }
}

console.log(secondaryObject);

Answer №1

When dealing with nested properties that are arrays of objects instead of objects, you cannot access them using dot notation. Instead, you need to access them by index. Here's an example to demonstrate:

const sampleData = {
  action: "Open Browser & Login",
  password: "something",
  url: "https://***manage",
  user: "user1",
}

var elementsData = {
  pages: [{
    groups: [{
      elements: []
    }]
  }]
};

for (var key in sampleData) {
  if (sampleData.hasOwnProperty(key)) {
    const element = {
      label: key,
      value: sampleData[key]
    };
    elementsData.pages[0].groups[0].elements.push(element);
  }
}

console.log(elementsData);

Answer №2

Each of your pages, groups, and elements within your data structure are arrays containing objects. In order to set a value, you must reference the specific array element by using index [0]:

var mElementsData = {
  pages: [{
    groups: [{
      elements: [{}]
    }]
  }]
};

var oValues = {
  key: "value"
};

for (var key in oValues) {
  if (oValues.hasOwnProperty(key)) {
    mElementsData.pages[0].groups[0].elements[0]["label"] = key;
    mElementsData.pages[0].groups[0].elements[0]["value"] = oValues[key];
  }
}
console.log(mElementsData);

Answer №3

Web pages and online communities are considered as an array, requiring a loop to bind objects in key-value pairs.

var websiteData = {
   pages: [{
        groups: [{
            elements: [{}]
        }]
    }]
};

var userInput = {
    action: "Start Task",
    password: "mypassword",
    url: "https://***manage",
    user: "username123",
}

for (var key in userInput) {
    if (userInput.hasOwnProperty(key)) {
        for (let i = 0; i < websiteData.pages.length; i++) {
            let pages = websiteData.pages[i]
            for (let j = 0; j < pages.groups.length; j++) {
                pages.groups[j].elements[j][key] = userInput[key]
            }
        }
    }
}
console.log(websiteData)

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

What is the most effective method for accurately tallying the number of matches in a Datalist using the Input value as a reference

I have set up a datalist element with an associated input element for autocompletion in modern browsers: HTML code <input type="search" id="search" list="autocomplete" /> <datalist id="autocomplete"> <option value="c++" /> < ...

What is the process for accessing and modifying cookies in a local file:/// HTML document?

What is the most effective method for reading/writing cookies in a local file:/// HTML document using JavaScript or jQuery? I attempted the following: function setCookie(c_name, value, exdays) { var exdate = new Date(); exdate.setDate(exdate.getDate( ...

Vue's v-for loop updates all input fields instead of just one, ensuring consistency across the board

After spending hours on this issue, I am still stuck and unable to find a solution through Google search. The problem lies in my v-for loop where I am iterating over an array of objects. Each iteration renders input fields displaying the name and price of ...

Guide on uploading files using Vue.js2 and Laravel 5.4

I'm currently attempting to implement an image upload feature using Laravel for the backend and Vue.js2 for the frontend. Here are snippets from my code: addUser() { let formData = new FormData(); formData.append('fullname', this.n ...

Tips for effectively handling a prop in an HTML form using Vue.js and avoiding infinite loops with a computed property

I have a Vue.js form for signing up that features numerous similar fields. From my understanding, I should initialize the values as props rather than objects or arrays (since they will be pass-by-value). My approach involves using a computed property with ...

Actively toggle the selection state within OpenSeadragon

Currently, I am in the process of integrating a viewer for scanned pages using OpenSeadragon along with the Selection plugin (https://github.com/picturae/openseadragonselection) to allow users to select a portion of the page. I have successfully incorpora ...

Save the location of the image in the database or dynamically create them according to the unique identifier

After revamping some code and getting rid of the old spaghetti mess, I am now dealing with a new challenge: I have TV episodes that come with a main screenshot source file and 4 thumbnails. The current process generates the paths for these thumbnails duri ...

Having issues with npm python-shell integration within electron framework

I'm currently attempting to establish a connection between a python script and an Electron app by utilizing the npm's python-shell package. The requirement is for the script to be executed whenever a button is clicked. So, let's assume my d ...

Creating an ngInclude directive on the fly: A step-by-step guide

Whenever I insert this into my HTML, everything functions correctly: <div ng-include="'my-template.html'"></div> However, when attempting to dynamically create that ngInclude directive using jQuery (after the DOM has loaded), it fai ...

The menu is loaded dynamically by Ajax from JavaScript once the page is refreshed

$('#subregionListPage').bind('pageinit', function(event){ var output = $('#subregions'); var region = getUrlVars()["reg"]; $.ajax({ url: 'http://localhost:8888/my/getsubregions.php', dat ...

Having trouble transmitting a file from the frontend to the server in your MERN project?

Struggling to transfer an image file from the React frontend to the server and encountering issues with sending the file: Below is the front end code snippet: useEffect(()=>{ const getImage=async ()=>{ if(file){ ...

Choose from the options provided to display the table on the screen

One of the challenges I am facing involves a table with two columns and a select option dropdown box. Each row in the table is associated with a color - green indicates good, red indicates bad, and so on. My goal is to have all values displayed when the pa ...

Calculating and displaying the output on an HTML page: A step-by-step guide

Within my HTML, I have two values stored in Session Storage: "Money" and "Time". These values are based on what the user inputted on a previous page. For example, if someone entered that they need to pay $100 in 2 days. My goal is to generate a list that ...

Prevent duplication in HTTP POST requests using Express and Node.js

How can I prevent a duplicate object from being created during a post request if the object already exists? I have included my code and JSON object below. I attempted to use next(), but it did not work as expected, resulting in a new object with a differen ...

The debounced function in a React component not triggering as expected

I am facing an issue with the following React component. Even though the raiseCriteriaChange method is being called, it seems that the line this.props.onCriteriaChange(this.state.criteria) is never reached. Do you have any insights into why this.props.onC ...

Utilizing AngularJS to selectively filter objects based on specific fields using the OR operator

My collection includes various items with different attributes. For instance, here is the information for one item: {"id":7,"name":"ItemName","status":"Active","statusFrom":"2016-01-04T00:00:00","development":"Started","devStartedFrom":"2016-01-04T00:00:0 ...

A JSON response that starts with a null value

After saving a JSON response to a file, I encountered an issue where the retrieved data had a null value preceding the JSON object. This was quite strange. 05-30 16:35:16.454: W/System.err(21734): org.json.JSONException: Value null of type org.json.JSONO ...

How can I transform the overall value into a percentage in Vue.js or JavaScript?

Is there a way to create a progress bar in VueJS 3 with Nuxt Js by converting the total value to a percentage and displaying it as a style width value? For example, if 40% out of 100% equals 400USD out of 1000USD, can we achieve this using a function in an ...

What could be causing the issue with ng-show in Angular?

When a user clicks on an icon, I want to display a drop-down menu. I attempted to use the ng-show directive for this purpose, but unfortunately, the drop-down menu is not appearing. I created an icon ..., and when clicked, I attempted to open the drop-do ...

Guide on utilizing angularjs $q.all() method with a dynamically generated set of promises

I am currently facing an issue with using $q.all() to wait for multiple promises to be resolved. I have created an array of promises and passed it to the all() method, but it doesn't seem to be working as expected. The promises in the array are gener ...