Techniques for navigating unidentified JSON structures using JavaScript

Currently, I am faced with the challenge of parsing the given data:

{
  'unknown-value': {
    name: 'AB',
    id: 'BLUE'
  },
  'unknown-value': {
    name: 'AC',
    id: 'PURPLE'
  }
}

My objective is to parse this data and then generate arrays of values like the following:

names = ['AB', 'AC']
ids = ['BLUE', 'PURPLE']

This scenario is a bit different from what I have encountered before, as it does not involve an array of objects. Therefore, I am currently unsure of the best approach to take.

Answer №1

  • To iterate through an array of objects, use the forEach method.
  • Retrieve the values of the object using Object.values().
  • Then, use forEach to loop through these values and push them into separate arrays for names or ids.

   
const obj = [{
  'unknown-value': {
    name: 'AB',
    id: 'BLUE'
  },
  'unknown-value2': {
    name: 'AC',
    id: 'PURPLE'
  }
}]

let names = [];
let ids = [];

obj.forEach((x) => { 
Object.values(x).forEach((y)=>{
  names.push(y.name);
  ids.push(y.id);
 })
})

console.log(names);
console.log(ids);

Answer №2

Don't overlook the importance of having that mysterious key handy - Object.entries is a valuable tool:

const transformed = Object.entries(data).map(([key, val]) => ({key, ...val}));

The transformed array now holds objects, each featuring a fresh "key" property denoting the original key.

Answer №3

const { firstNames, lastNames, } = Object.values({

  'foo': {
    firstName: 'John',
    lastName: 'Doe',
  },
  'bar': {
    firstName: 'Jane',
    lastName: 'Smith',
  }
}).reduce((map, item) => {

  map.firstNames.push(item.firstName)
  map.lastNames.push(item.lastName)

  return map;

}, { firstNames: [], lastNames: [] });

console.log('firstNames :', firstNames);
console.log('lastNames :', lastNames);
.as-console-wrapper { min-height: 100%!important; top: 0; }

Answer №4

Give this method a try and watch as the desired outcome unfolds effortlessly

data = {
  'mystery-data': {
    label: 'X',
    code: '123'
  },
  'mystery-data': {
    label: 'Y',
    code: '456'
  }
};

labels = [];
codes = [];

for (index in data) {
    labels.push(data[index].label);
    codes.push(data[index].code);        
}

for (item of labels) {
    console.log(item);
}

for (item of codes) {
    console.log(item);
}

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

Utilizing JavaScript to handle the value from a selected form

My form is quite simple: <form id="signup"> <div class="form-group"> <input type="text" name="email" placeholder="Email" id="email" required> </div> <div class="form-group"> <input type= ...

What limitations prevent the Jersey/JAX-RS client from effectively processing generics?

I am currently working with a Jersery/JAX-RS client that interacts with a RESTful API (JSON), specifically designed to retrieve a list of my POJOs: // Hits: GET localhost:8080/myapp/fizz/widget/{widget_id} @Override public List<Widget> getWidgetsByU ...

Ways to make JSON-lib's JSONObject.put(..) escape a string with JSON content?

Is there a way to prevent JSON-lib's JSONObject put method from storing a String containing JSON as JSON itself rather than an escaped string? Example: JSONObject obj = new JSONObject(); obj.put("jsonStringValue","{\"hello\":\"world&b ...

Comparing the use of Next.js static assets from the public folder with cloud-based storage solutions

Typically, in Next.js (or React) cloud-based storage solutions are commonly utilized for storing media files such as images. My inquiry is, what prevents us from saving images as static assets in the public folder and accessing them directly in our appli ...

What is the most efficient way to use jQuery to retrieve the count of tags associated with a variable

I am trying to filter my data retrieved from ajax using a function. Here is the initial code: var csvf = data.filter(function (el) { return ['TRUCK_CPX'].indexOf(el.TAG) >= 0 && ['CA5533'].indexOf(el.Chave) >= 0 }); Now ...

What is the best way to retrieve a document element in React when utilizing an external script?

In my React project, I have successfully implemented a chat button using an external script. However, I encountered an issue where I needed to hide the chat button on specific pages. Since I couldn't access the button's element using a ref, I res ...

The JMeter JSR223 Sampler and WebDriver Sampler do not support the Javascript language

I am currently working on integrating Selenium Webdriver Sampler with JMeter. Although I have been following tutorials, I have encountered an issue where the script language dropdown in the sampler screen does not include an option for JavaScript, prevent ...

Issues encountered while optimizing JSON file in a ReactJS program

I'm struggling with utilizing Array.prototype.map() in Javascript Specifically, I'm reformatting a JSON file within my react app, which looks like: { "id": 1, "title": "Manage data in Docker", "description": "How to use v ...

What is the method for dynamically updating and showcasing a JSON file upon the click of a button?

I'm currently developing an add-on that will display a panel with checkboxes and a save button when a toolbar button is clicked. The goal is to allow users to select checkboxes, then save the selected data in a JSON file that can be accessed and updat ...

Fetching Json data from PHP server

Here is the Json data provided:- {"data":[{"text1":"value1","text2":"value2","text3":"values3"},{"text1":"value1","text2":"value2","text3":"values"},{"text1":"value1","text2":"value2","text3":"values"},{"text1":"value1","text2":"value2","text3":"values"}, ...

React-easy-crop simply provides a blob url as a result

Currently, I am utilizing the react-easy-crop package to enable users to make adjustments to their profile pictures post uploading. However, I have encountered an issue where the cropped image is returned in the form of a blob URL such as blob:http://local ...

What additional requirements are needed for Rails and remote AJAX with the "true" setting?

I'm a bit confused about the purpose of remote:true in Rails forms. I initially thought that it required some Javascript to enable asynchronous functionality, but instead it seems to be causing issues with my page. Below is a simple index.html.haml f ...

Building a GWTP table from scratch

Exploring the world of GWTP has been quite a learning experience for me. I recently attempted to create a table that would display JSON values using Piriti mappers. While this code snippet is not from an actual project, it serves as my attempt to grasp the ...

What is the best approach for updating data in a v-data-table dynamically?

I'm currently working on a node and electron application that utilizes vuetify to create a table (v-data-table) fetching data from an oracle database. The issue I'm facing is that even though the data changes based on the input value, the table f ...

Tooltips will display on all Nivo charts except for the Nivo Line chart

I'm having an issue with nivo charts where the tooltip isn't showing up for my line chart. Even after copying and pasting the example from here: Other chart examples work fine with tooltips appearing, but for some reason, it's just not work ...

Leveraging both onmouseover and onmouseout for container expansion

My goal is to utilize JavaScript along with the HTML events "onmouseover" and "onmouseout" to create a dynamic container. Essentially, I want the container to act as simply a heading when the mouse is not hovering over it, but expand to display additional ...

Error: Unable to access attributes of null object (specifically 'accessToken')

After following a YouTube tutorial by Lama for creating an E-commerce application, I attempted to add a logout feature on the admin page that was not covered in the tutorial. To implement this, I used Redux to grab the currentUser and set it to null to suc ...

Using React Native to integrate a JSON string into a button

I'm currently working on an app to explore the functionality of websockets in react native. I have successfully retrieved data from the websocket in JSON format and can output it to the console using console.log. However, my goal is to display a speci ...

Interactive Thumbnail Selection for HTML5 Video

Having trouble with creating thumbnails? I managed to solve the cross-domain issue using an html2canvas PHP proxy. No error messages in the Console, but the thumbnails are unfortunately not showing up - they appear transparent or white. Here is a snippet ...

Sending blank data using ExpressJS ajax feature

I am encountering an issue while trying to send JSON data to my server as the POST requests are coming through with empty bodies. Below is the TypeScript code I am using on the front end: function sendData() : void { console.log("Sending data..."); var na ...