Tips on storing JSON string array with multiple name/value pairs in distinct arrays using JavaScript

Below is a JSON string that I have:

[ { "id" : "1", "name" : "name1" },
{ "id" : "2", "name" : "name2" },
{ "id" : "3", "name" : "name3" },
{ "id" : "4", "name" : "name4" },
{ "id" : "5", "name" : "name5" } ]

Is there a way to split this data into two separate arrays, one for "id" and one for "name", while still maintaining the same data at each index?

Answer №1

const sampleData = [ { "id" : "1", "name" : "John Doe" },
{ "id" : "2", "name" : "Jane Smith" },
{ "id" : "3", "name" : "Alice Johnson" },
{ "id" : "4", "name" : "Bob Brown" },
{ "id" : "5", "name" : "Emily Davis" } ];

const idsArray = sampleData.map(function(item){
      return item.id;
});

const namesArray = sampleData.map(function(item){
      return item.name;
});

Transform data using the map function

Answer №2

Your inquiry is somewhat unclear, but the following code may provide a starting point to help you achieve your objective.

Utilizing the forEach function can easily assist in this task.

var ids = [];
var names = [];
data.forEach(function(obj) {
 ids.push(obj.id);
 names.push(obj.name);
});

If you also wish to utilize the map function

var ids = data.map(function(obj){
  return obj.id;
});

var names = data.map(function(obj){
  return obj.name;
});

However, if cross compatibility is crucial, consider employing a standard for loop.

var ids = [];
var names = [];
for (var i in data) {
 ids.push(data[i].id);
 names.push(data[i].name);
}

Expected Output

["1", "2", "3", "4", "5"] // ids

["name1", "name2", "name3", "name4", "name5"] // names

Answer №3

This method of processing is designed to handle a variable number of elements efficiently.

var data = [{
  "id": "1",
  "name": "name1"
}, {
  "id": "2",
  "name": "name2"
}, {
  "id": "3",
  "name": "name3"
}, {
  "id": "4",
  "name": "name4"
}, {
  "id": "5",
  "name": "name5"
}];
// key parameter is optional.
// If key is provided, only the array with that key is returned.
// Otherwise, the entire structure is returned.
function processArray(data, key) {
    var result = {},
      i,
      prop,
      length = data.length;
    for (i = 0; i < length; i += 1) {
      element = data[i];
      for (prop in element) {
        if (!result[prop]) {
          result[prop] = [];
        }
        result[prop].push(element[prop]);
      }
    }
    if (key) {
      return result[key];
    }
    return result;
  }
  // Output the array containing "id" only.
console.log(processArray(data, "id"));
// Output the entire structure.
//console.log(processData(arr));

Answer №4

let products = [ { "id" : "101", "name" : "product1" }, { "id" : "102", "name" : "product2" }, { "id" : "103", "name" : "product3" }, { "id" : "104", "name" : "product4" }, { "id" : "105", "name" : "product5" } ];

let output = {
  productNames: [],
  productIDs: []
};
products.forEach(item => {
  output.productNames.push(item.name);
  output.productIDs.push(item.id);
});
console.log(output);

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

Refreshing Bootstrap-Vue Table does not result in updating the table with table.refresh() method

I am facing an issue with a table that is supposed to be updating its data dynamically. The scenario is such that when a button is clicked in the parent component, a server call is triggered and a JSON file is loaded into a child component (the table) via ...

Detecting collisions using CSS animation

I'm currently working on a unique "game" project. Check out the code snippet here: jsfiddle function update() { coyote.applyForce(gravity); coyote.edges(); coyote.update(); cactus.update(); if (coyote.intersects(cactus)){ alert("colisio ...

Using the Croppie plugin to crop an image before uploading via jQuery Ajax in PHP

I've successfully implemented a code snippet that allows image cropping using PHP, jQuery, and Ajax with the Croppie plugin. Currently, I'm facing an issue while trying to include additional input values along with the image upload process. I ...

A guide on utilizing getStaticProps to map a collection obtained from Strapi within a Next.js component

I'm currently following a tutorial on YouTube that teaches how to create a basic blog using Next.js and Strapi. The code snippet below is used to fetch post data from Strapi, but it's not working as expected because the .map function can only be ...

Using Node.js to alter an existing JSON file

I have a file named a1.json that contains the following data: { "Key1" : [ { "Key11" : "Value11" , "Key12" : "Value12" }, { "Key21" : "Value21" , "Key22" ...

Retrieve a collection of objects from JSON using Gson

How can I parse a json array using Gson? My json string contains an array of objects (filters array) along with other objects and fields. Here is the structure of my json file: { name: "test json", test_ob: { name: "test" }, filters [ { ...

JavaScript plugin designed for effortless conversion of JSON data to structured HTML code

I want to add this JSON data to an HTML element. [ { "website":"google", "link":"http://google.com" }, { "website":"facebook", "link":"http://fb.com" } ] Is there an easy way to convert this using a plugin ...

Ways to avoid scrolling on a fixed element

Here is the HTML setup I have... body .top .content The issue I am facing is that when scrolling reaches the end of the ul in the .top element, the background starts to scroll. This can be quite disorienting and makes the site slow on tablets. Even ...

Requesting data from server using Ajax with multiple JSON responses

I'm facing a situation where my Ajax script calls a PHP file to make a query to MySQL and then formats the response in JSON. The challenge is that I need to retrieve data from different tables based on the id sent with the Ajax call. Some tables retur ...

jQuery setup for doWhen

Struggling to get doWhen functionality to work properly. Here is my index.html setup: <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <script type="text/javascript" src="js/jquery.dowhen.min.js"></sc ...

What is the process for triggering a function event on click (or any other function) within a browser's activation?

Some time ago, I was trying to figure out why the onclick event wasn't working when I clicked on a specific area of the browser. After consulting a guide, I discovered the issue and fixed it. It turns out that the problem was quite simple, and now I u ...

Anonymous self-executing functions with parameters from an external scope

Recently, I stumbled upon the code snippet below while following a tutorial. const increment = (function(){ return function incrementbytwo (number){ return number+2; } })(); console.log(increment(1)); The result of the code above is 3. ...

Implementing JSON responses in Express JS

My apologies for any language errors as English is not my first language, I am using Google Translate :) I have a question.. Here is the MySQL Query I am working with: SELECT destinations.*, questions.*, answers.* FROM destinations INNER JOIN questions ...

Ways to verify the timeframe between two specific dates

Having two distinctive arrays: accomodation: [ { id: 1, name: "Senator Hotel Fnideq", address: "Route de Ceuta, 93100 Fnidek, Morocco", checkin: "September 1", fullCheckinDate: "2021-09-01", ...

Unable to retrieve content using the query.ID in Next.js

I'm trying to figure out what is causing the issue in this code, but I can't seem to resolve it. My goal is to use the query.id inside getInitialProps to fetch some content. The fetching process works fine, but when an error occurs, I receive thi ...

Employing ng-click within a displayed column of Datatable

Currently, I am utilizing a plain Datatable in AngularJS without any Angular-Datatable libraries. Everything appears to be working well except for one issue. Here is the datatable code snippet: $scope.siInfoTable = $('#siInfoTable').DataTable({ ...

What is the proper way to enable the Google Analytics cookie only once another consent cookie has been set and is marked as "true"?

I am currently using React/Nextjs on my website along with the react-cookie-consent library. This setup generates a pop-up where users can agree to the cookie policy, and if they do, a CookieConsent with the value "true" is set. In addition to this, I wis ...

What is the method to retrieve text from a div element with Webdriver-IO?

Is there a way to extract the value from the following HTML element using Webdriver-IO for automated testing? <div class="metric-value ng-binding" ng-style="{'font-size': vis.params.fontSize+'pt'}" style="font-size: 60 ...

What is the best way to include a JavaScript variable in an HTML image src tag?

Even though I know the answer to this question is out there somewhere, I just can't seem to find it (or maybe I'm not recognizing it when I see it!). As a beginner in jquery, please be patient with me. Dilemma: I have a collection of 20 images, ...

Searching for the name of dynamically generated input fields using jQuery

I have a straightforward form featuring radio buttons <form> <input type="radio" name="radio_1" value="1" />Radio 1 <input type="radio" name="radio_1" value="2" />Radio 2 <input type="radio" name="radio_1" value="3" />Radio 3 </ ...