Tips for adding JSON values to an object

There is a specific object called SampleObject which has the following structure:

{
   ID: "", 
   Name: "", 
   URL: "", 
   prevName: "",
   Code: "",
}

I am looking to insert the values from the JSON object below (values only):

var object =
{
"Sample" : {
    "Data" : {
        "ID" : "12345",
        "Name" : "SampleName: Name",
        "URL" : "www.google.com",
        "prevName" : "phones",
        "Code" : "USD"
    } 
}

into the predefined object mentioned above. How can this be achieved?

Answer №1

To incorporate values from an object, consider using a loop like for in to check if the key exists before setting its value.

First, validate if the property is present in the emptyObject and then transfer the value accordingly.

for (var key in dataInfo) {
  var val = dataInfo[key];

  if (newObj.hasOwnProperty(key)) {
    newObj[key] = val;
  }
}

Visit Code Pen for demonstration

Answer №2

This item is an object that does not require the use of push or any other method.

All you need to do is take your specified object pageObject.page and add a new key value pair using literal syntax.

pageObject.page['pageInfo'] = predefinedObject

Alternatively, you can use a more conventional syntax like this:

pageObject.page.pageInfo = predefinedObject

Answer №3

Below is the code to be used after the JSON Object:

let data = {website: {info:''}};
data.website.info = websiteObject.website.info;
console.log(data.website.info);

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 best way to display an Error 404 page in a statically rendered client-side page using Next.js?

import { onAuthStateChanged } from "firebase/auth"; import Link from "next/link"; import { useRouter } from "next/router"; import { useEffect, useState } from "react"; import { auth } from "../../lib/firebase&qu ...

Encountering the Error "PLS-00201: identifier 'JSON_VALUE' needs to be declared" while using PL/SQL

I am facing a challenge in extracting data from a Json file stored within a table. I am encountering difficulties when trying to run the JSON_VALUE package inside PL/SQL. The following query runs successfully: SELECT JSON_VALUE('{a:100}', &apos ...

Using JavaScript to assign the title property to an <a> tag

I'm currently working on modifying a code snippet that utilizes jQuery to display the "title" attribute in an HTML element using JavaScript: <a id="photo" href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" data-gallery><i ...

jQuery does not support animations for sliding up or down

I'm struggling to conceal a navigation element once the top of the #preFooter section is scrolled to. In order to make the nav element mobile-friendly, I have designed both the .tab-wrap and .tab-wrap-mobile. To enable these elements to slide away w ...

Every time I attempt to submit data, I encounter a 404 error with AXIOS

Struggling to figure out why I keep encountering an error when trying to send form data from my website to the database using axios? Despite attempting various solutions, the problem persists. Although I can successfully retrieve manually entered data from ...

What is the reason that preventDefault fails but return false succeeds in stopping the default behavior

I'm having trouble with my preventDefault code not working as expected. While using return false seems to work fine, I've heard that it's not the best practice. Any ideas why this might be happening? if ($('.signup').length == 0) ...

Determine the prior location of an element using jQuery

Is there a way to track the previous location of an element before it is appended? I have 50 elements that need to be appended to different targets based on a certain condition. How can I determine where each element was located before being moved? $(&a ...

I am unable to retrieve any information from the JSON request

When I send JSON data to a specific route, below is the code I use: const data = [{ name: this.name }] axios .post('/users', { name: this.name }) .then( response => { console.log(response.data); } ) ...

Once invoked by an ajax request, the $().ready function is executed

The functionality of this code is flawless when running on its own. However, once I make an ajax call to it, the code fails to execute. I suspect that the issue lies within $().ready, but I haven't yet identified a suitable replacement. Any suggestio ...

The Vue-cli webpack development server refuses to overlook certain selected files

I am attempting to exclude all *.html files so that the webpack devserver does not reload when those files change. Here is what my configuration looks like: const path = require('path'); module.exports = { pages: { index: ...

Is it necessary to send form data back with Express, or is there an alternative solution?

I am facing a simple problem with my handlers for /login get and post requests. Here is the code: loginRender(req, res) { let options = { title: 'Login', layout: 'auth.hbs' } res.render('login', options) } logi ...

Trouble displaying static files in Angular/Express app on Heroku, while they are functioning as expected on local environment

After deploying to Heroku, I noticed that the css and javascript files in the 'public' directory were missing, resulting in 404 errors. Strangely, these files exist locally without any issues. In my app.js file, I have included the following: a ...

Why is the console log not working on a library that has been imported into a different React component?

Within my 'some-library' project, I added a console.log("message from some library") statement in the 'some-component.js' file. However, when I import 'some-component' from 'some-library' after running uglifyjs with ...

Display the HTML content once the work with AJAX and jQuery has been successfully finished

Below are the codes that I have created to illustrate my question. It's not a complete set of code, just enough to explain my query. The process goes like this: HTML loads -> calls ajax -> gets JSON response -> appends table row with the JSO ...

Should the method of creating a Dropdown with Angular be considered a poor practice?

I've recently dived into Angular and successfully created my first dropdown using it, which is working great. However, I'm a bit concerned about the number of comparisons being made and wondering if this approach is considered bad practice. The ...

Specify that a function is adhering to an interface

Is there a way in Typescript to ensure that a function implements a specific interface? For example: import { BrowserEvents, eventHandler, Event } from './browser-events'; export function setup(){ const browserEvents = new BrowserEvents(); b ...

Tips for enhancing the presentation of JSON information

I recently ventured into the world of JSON and JS, managing to create a JSON file to showcase data using .onclick event. While I have successfully generated and displayed the JSON data on screen, my next goal is to present it in a table format for better c ...

Customizing event colors in Full Calendar

My interactive calendar is created using : $('#calendar').fullCalendar({ height: 300, //............. events: jsonData, month: firstMonth }) I am looking to dynamically change the color of an event based on certain conditions ...

Error: Unable to access the 'classList' property of null in HTMLSpanElement.expand function

Encountering a minor issue with my javascript code. Following a tutorial for a seemingly simple task: link What I did: Adapted the HTML from the tutorial to fit my desired visual outcome while maintaining correct class and id attributes. Utilized identic ...

Sorting through an array using a different array of values

Looking to filter one array with another, where values in the first array should match 'id' in the second array for filtering. The arrays in question are: const array1 = [a, b, c, d] The array to be filtered based on matching 'id' va ...