Is it possible to extract a nested JSON value and append it outside of the nested object?

Apologies for my inability to find more suitable phrasing for my question.

The scenario is this - I have a nested JSON structure, and for some reason, I need to extract the value of a nested key-value pair object and place it outside the JSON.

JSON example:

DataSource=  [
      {
        "a": 1,
        "name": "jack",
        "version": 1,
        "Id": "39da",
        "active": false,
        "userId": "jack_user",
        "properties": [
          {
            "id": 7080,
            "key": "country",
            "value": "in",
          },
    {
            "id": 7081,
            "key": "state",
            "value": "xyz",
          },
    ]}]

Desired JSON output:

 DataSource=  [
      {
        "a": 1,
        "name": "jack",
        "version": 1,
        "Id": "39da",
        "active": false,
        "userId": "jack_user",
    "country": "in"
        "properties": [
          {
            "id": 7080,
            "key": "country",
            "value": "in",
          },
    {
            "id": 7081,
            "key": "state",
            "value": "xyz",
          },
    ]}]

Although I can iterate over the entire JSON using the code below, I am struggling to select an object from the Properties array.

 for (var i = 0; i < this.DataSource.length; i++) {
          var tempDataSource = this.DataSource;
          console.log(tempDataSource );

Answer №1

To achieve the desired outcome, you can follow this approach assuming the data array contains only one object.

const data = [
  {
    "a": 1,
    "name": "jack",
    "version": 1,
    "Id": "39da",
    "active": false,
    "userId": "jack_user",
    "properties": [
      {
        "id": 7080,
        "key": "country",
        "value": "in",
      },
      {
        "id": 7081,
        "key": "state",
        "value": "xyz",
      },
    ]
  }
]

data[0].properties.forEach(obj => {
  if (data[0][obj.key] == 'country') {
    data[0][obj.key] = obj.value
  }
})

console.log(data)

The output will be:

[
  {
    "a": 1,
    "name": "jack",
    "version": 1,
    "Id": "39da",
    "active": false,
    "userId": "jack_user",
    "properties": [
      {
        "id": 7080,
        "key": "country",
        "value": "in"
      },
      {
        "id": 7081,
        "key": "state",
        "value": "xyz"
      }
    ],
    "country": "in"
  }
]

Answer №2

Feel free to test out my code snippet below:


          const data = [{
            "a": 1,
            "name": "jack",
            "version": 1,
            "Id": "39da",
            "active": false,
            "userId": "jack_user",
            "properties": [{
                "id": 7080,
                "key": "country",
                "value": "in",
              },
              {
                "id": 7081,
                "key": "state",
                "value": "xyz",
              },
            ]
          }];

          console.log('Before:', data);

          data[0][data[0].properties[0].key] = data[0].properties[0].value;

          console.log('After:', data);
          

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

How to Send a Multi-part Message Using AT Commands and PDU Mode in Node.js

I am trying to send a multipart message using AT commands. Single parts work fine, as do special characters. However, when the message exceeds 160 characters, it shows as sent but nothing is received. const async sendSMS(msisdn, message) { message += ...

struggling with managing an array of Vue3 refs

Having an issue with handling vue3 refs, specifically when retrieving data from Firestore. When logging the [documents], everything seems to work fine. However, I run into errors when trying to access values from an array within a document. For example, ...

Exploring how JavaScript variables behave when used inside a nested forEach loop with an undefined

While inside the second for loop, I am attempting to retrieve the value of this.userId. However, it is returning undefined. Let's take a look at the code snippet below: // The following variable becomes undefined within the second for loop this.userI ...

Utilizing dynamically loaded JSON data in Vue 3 templates

Within my Vue3 view, I encounter the need to dynamically import JSON data based on the browser URL. This means that the JSON filename will vary depending on the URL, such as domain.com/canada utilizing canada.json and domain.com/usa utilizing usa.json, all ...

Why is it that when I store a DOM element reference in a JavaScript Array, I cannot reuse that stored reference to add an event listener

I have a little confusion and I hope someone can help me out. I am facing an issue with dynamically created buttons, where each button has a unique id. To keep track of these buttons in a well-organized manner, I store their references using a simple two-d ...

There seems to be a problem with the rendering of select options

React Component for Region Selection import React from 'react'; import { getRegions } from '../helpers' class RegionSelect extends React.Component { constructor(props) { super(props); this.state = { regions: [], ...

ajax ignores output from php

I've been working on passing PHP echo values through AJAX, but I've encountered a problem where the if and else conditions are being skipped in the success function of AJAX. Even when the if condition is met, the else statements are still being e ...

Why do we often encounter a "SyntaxError: Unexpected token ;" error when a seemingly normal semicolon is present in distribution files?

Currently, I am in the process of developing a newsletter subscription API using node.js and typescript. This project involves my first experience with typeorm and PostgreSQL. Following several tutorials, I configured typeorm and created the entity types a ...

The Electron BrowserWindow turns dark post execution of the .show() method

Revision: After some tinkering, I discovered that the issue was related to the order in which I created the windows. Previously, my code looked like this: app.whenReady().then(() => { createWindow(); spawnLoadingBlockWindow(); spawnGenerati ...

Troubleshooting JSON Parsing: No data is displaying in Kilometers

As a new programmer, I am exploring the Google Matrix API. Upon receiving the response, I am trying to extract the value of "text" as "1686 km" using Json Parsing. Thank you "destination_addresses" : [ "San Francisco, Californie, États-Unis" ], ...

Is it possible to dynamically assign a template reference variable to a newly created DOM element in TypeScript?

After creating a DOM element with this.document.createElement('h1'), I am looking to insert the element into a section tag using a template reference variable (myTRF), similar to the example below: <section> <h1 #myTRF>This is my he ...

Angular Material's autocomplete feature allows users to easily search

I am currently working on creating an Angular Material Autocomplete feature. At the moment, I have successfully displayed the options and when selected, the correct name is inserted into the input field. However, my next task is to enable filtering of the ...

Obtaining a reference to a filtered result in ngRepeat with AngularJS

Using an ng-repeat directive with a filter, the code looks like this: ng-repeat="item in items | orderBy:'order_prop' | filter:query | limitTo:4" The rendered results are visible; now the goal is to perform some logic on that result in the cont ...

Push-grid interaction through drag-and-drop feature

I'm on a quest to incorporate grid drag-and-drop functionality into my project. While there are numerous frameworks available that offer this feature, one of the most popular options is JQuery UI's sortable library. However, I am specifically lo ...

Coordinates of a vertex's position within a grouped Object3D Geometry

For the past 7 hours, I have been diligently exploring all possible combinations based on the solutions provided in this thread: How to get the absolute position of a vertex in three.js? My current task involves identifying the exact positions of vert ...

I keep experiencing a NetworkOnMainThreadException when trying to obtain the latitude and longitude

Is there a way to retrieve longitude and latitude by sending a string to Google Geocode and receiving JSON data in return? Whenever I attempt this, I encounter a NetworkOnMainThreadException. What could be causing this issue and how can it be resolved? pu ...

Leverage the power of Angular and Node.js to dynamically generate and configure a new subdomain on an

Currently, I am tackling a project that involves generating sub domains dynamically based on the prefixes entered by users on my website. While everything is functioning properly on my localhost using diet.js and express-subdomain, errors are being encount ...

Node Express and Typescript app are failing to execute new endpoints

Hello, I'm currently diving into Node express and working on a simple CRUD app for pets. So far, I've successfully created 2 endpoints that are functioning properly. However, whenever I try to add a new endpoint, Postman fails to recognize it, g ...

Encountered Axios Error: Network Connection Failure and CORS Challenge while working in React

I'm attempting to call the API located at . Unfortunately, I am encountering an error in the console of the developer tools: Access to XMLHttpRequest at 'https://api.wisecapitals.com/cronjobs/fetchXERate' from origin 'http://localho ...

Moving points from a .obj model that was brought in

Being new to three.js, I've been stuck on a rookie mistake for hours. After finding some useful examples of mesh editing and managing an imported model on the forum (link), I tried adapting my code based on this example but now I'm facing a probl ...