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

Basic use of AJAX for sending the value from jQuery's datepicker

As a novice in JavaScript and AJAX, I'm hoping for your patience as I navigate my way through. In the scope of this project, I am utilizing the CodeIgniter framework. My objective is to implement a datepicker and transmit its value via AJAX. Below is ...

What is the best way to update or reload an embedded application/pdf?

I have implemented an embed code using application/pdf in order to display a pdf document on the website. To dynamically change the src attribute of the embed when a link is clicked, I utilized javascript. I confirmed this action by displaying alerts to e ...

What is the best way to toggle the visibility of a side navigation panel using AngularJS?

For my project, I utilized ng-include to insert HTML content. Within the included HTML, there is a side navigation panel that I only want to display in one specific HTML file and not in another. How can I achieve this? This is what I included: <div ng ...

Is it possible to trigger a script tag based on certain conditions using a JavaScript function?

I'm currently working with Angular and have a requirement to trigger a third party script from a function located within another script tag. Here's an example scenario: Within the index.html file let displayOnHomepage = () => { if (win ...

Adding JSON data to an existing JSON file in Node.js can be done using the `fs

What is the best way to add data to an existing JSON file with a comma as a separator? anchors = [ { "title":" 2.0 Wireless " } ] fs.appendFileSync('testOutput.json', JSON.stringify(anchors)); The output of the current code looks like this ...

Adding specific key, value pairs to a python dictionary by extracting data from a json file

I am facing an issue where I need to extract a specific key and value from a JSON file in Python and add it to a dictionary. Currently, I have been able to successfully add all the data from the JSON file into my dictionary, but that is not the desired out ...

From JSON to PNG in one simple step with Fabric.js

I am looking for a way to generate PNG thumbnails from saved stringified JSON data obtained from fabric.js. Currently, I store the JSON data in a database after saving it from the canvas. However, now I want to create a gallery of PNG thumbnails using thi ...

Animating HTML 5 canvas with keydown events

As a newcomer to programming, I've been experimenting with HTML 5 and canvas. My goal is to make a simple rectangle move when a key is pressed, but I'm facing difficulties in achieving this. I tried following the instructions provided in this gui ...

What could be causing my selenium tests to fail on travis-ci even though there have been no code changes, when they are passing successfully

I'm facing a tough challenge trying to troubleshoot a selenium test that passes when run locally but not on travis. Reviewing the travis build logs, I noticed that the test was passing in build #311 but started failing at build #312. It seems like th ...

Is there a way to utilize classes in various elements when other jQuery selectors are not functioning properly?

Could someone please clarify or provide an alternative solution to the following situation: The class fruit is present in two different tag elements, and one of these elements has the add class used in a jQuery selector. However, the alert box is not disp ...

Discover the ultimate solution to disable JSHint error in the amazing Webstorm

I am encountering an error with my test files. The error message states: I see an expression instead of an assignment or function call. This error is being generated by the Chai library asserts. Is there a way to disable this warning in Webstorm? It high ...

Incorporating React.js into HTML DOM Elements

As a beginner in react js, I'm facing an issue regarding DOM elements. Within my component, there is a table. When hovering over a cell, I want to highlight both the corresponding row and cell. Additionally, I need to obtain the coordinates of the hov ...

Utilizing JsonQuery to retrieve organized JSON data within filter.js

I recently discovered the amazing filter.js script, which can be found at https://github.com/jiren/filter.js. It has been incredibly helpful in my projects. var FJS = FilterJS(products, '#products', { template: '#productfinder-template& ...

What is the best way to upload a JSON file onto a local server?

After struggling for the past two hours trying to solve a problem I encountered, I've come to realize that accessing a local JSON file named data.json from my project directory is not possible due to cross-origin requests limitations. In order to acce ...

What are the steps to clipping a canvas using CSS clip-path?

When it comes to clipping a canvas, there are multiple methods that can be used. One way is to create a path with getContext('2d') and set globalCompositeOperation. Another method involves using -webkit-clip-path or clip-path, though the latter m ...

What steps should I follow to successfully incorporate Zurb Foundation 4 Sections (tabs) into my Javascript Ajax functionality?

I am currently incorporating Zurb Foundation 4.1.5 into my application and I am faced with the challenge of implementing Zurb Section Javascript to handle "tabs" on the page. The content within these tabs is dynamic and fetched via Ajax calls. I am seeking ...

Leveraging an external TypeScript library in a TypeScript internal module

Imagine you find yourself in a situation where you need to utilize a typescript/node library within an internal module that is spanned across multiple .ts files. ApiRepositoryHelper.ts import * as requestPromise from "request-promise"; module ApiHelp ...

Creating a method for retrieving information from an API using Retrofit

Trying to figure out how to structure a model for an API output like this one: https://i.stack.imgur.com/YRDf8.png I've already created my model as shown below: package com.bertho.tdashboard.model; import com.google.gson.annotations.Expose; import ...

Storing data from a JSON file into a dictionary in Discord.py can be achieved by using the

In short, I am looking to store a dictionary called user_messages in a JSON file with the format {'user': amount_of_messages}. Later on, I want to be able to update the message count for each user by opening the file and saving it back to the JSO ...