Transforming data from a JSON format into a JavaScript array

I'm trying to convert a JSON string into an array containing the values from the JSON. When I use json.stringify(jsonmybe) and alert it, I see

[{"role":"noi_user"},{"role":"bert_user"}]
(which is in JSON format). My goal is to extract `noi_user` and `bert_user` and save them in a JavaScript array like ['noi_user','bert_user'], with quotes around each value.

After using var stringy = json.parse() and displaying the alert, I only see [object Object]. So, I added the following lines:

for (var i = 0; i < stringy.length; i++) {
    arr.push(stringy[i]['role']);
}

In the alert, I see `arr` as a single value with a comma missing between them. When displayed in a text field, it appears as one long string like noi_userbert_user.

Ultimately, I want to transform

[{"role":"noi_user"},{"role":"bert_user"}]
into ['noi_user','bert_user'].

Answer №1

To achieve your desired outcome, utilize JSON.parse and then apply the reduce function:

var data = `[{"role":"noi_user"},{"role":"bert_user"}]`

var roles = []
try {
  roles = JSON.parse(data).reduce((acc, val) => [...acc, val.role], [])
} catch (error){
  console.log("Invalid json")
}
console.log(roles)

Answer №2

Are you searching for this solution? You can iterate through your array and extract the role attribute from each data point.

const jsonData = ...
const dataArray = JSON.parse(jsonData).map(item => item.role);
console.log(JSON.stringify(dataArray, null, 2));

JSON utilizes double quotes to define strings and object keys.

Answer №3

Imagine you have a JSON string like this:

'[{"role":"noi_user"},{"role":"bert_user"}]'

Your goal is to convert it into an object, then extract the values of the "role" fields from each element and store them in an array.

The example JSON string contains an array of user objects with "role" fields. The code below takes this list, iterates through each user object, and adds the roles to a separate array called roleList.

var jsonStr = '[{"role":"noi_user"},{"role":"bert_user"}]';
    
var userObjList = JSON.parse(jsonString);
var roleList = [];
userObjList.forEach(userObj => {
    roleList.push(userObj.role);
});
console.log(roleList);

Answer №4

If you want to create a customized function in PHP that mimics the functionality of array_values but adds indentation and organizes the data into a 2D array, you can do so by following this example:

function custom_array_values_indented (input) {
  var temporaryArray = [];
  for (key in input) {
    temporaryArray.push(input[key]['role']);
  }
  return temporaryArray;
}

var objectData = JSON.parse('[{"role":"noi_user"},{"role":"bert_user"}]');
var output = custom_array_values_indented(objectData);
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

Determine if a point within a shape on a map is contained within another shape using Leaf

I have extracted two sets of polygon coordinates from a leaflet geoJSON map. These are the parent and child coordinates: var parentCoordinates=[ [ 32.05898221582174, -28.31004731142091 ], [ 32.05898221582174, -2 ...

Data is not being stored in Parse

I am currently facing a challenge while working with Parse for Javascript: When users sign up, along with their username and password, I also need to save their first and last names in Parse. However, at the moment, only the username and password are bein ...

Is there a Rust secp256k1 alternative to the `crypto::ECDH::computeSecret()` function in NodeJS?

After developing a functional NodeJS/Javascript function, I am now intrigued by the idea of achieving similar results using the Rust secp256k1 library: /* * Calculate the Symmetric Key from the Public and Secret keys from two * different key pairs. * ...

Displaying a variable in a live HTML user interface

I have successfully created a Python program that captures data from an Arduino Potentiometer and shows it on the Python console. Now, I am working on enhancing the output by displaying it in a local HTML file. I am seeking guidance on how to incorporate t ...

The Rails base file contains a function, let's call it function A, which calls another function, function C. However, function C is defined in two separate JavaScript files

My project includes an application_base.js file with a function: function drawLocations(canvas, blag, blah) { //do some stuff selectLocations(a_something, b_something); //do some stuff } For Page 1: page_1.js function selectLocations(a_somet ...

Arrange data in JSON file based on job title (role name) category

My current code successfully outputs data from a JSON file, but I'm looking to enhance it by organizing the output based on the "Role Name". For example, individuals with the role of Associate Editor should have their information displayed in one sect ...

What is the best way to combine a QR code and an existing image using Java script?

Looking for help in embedding a created QR code into an existing image. I am proficient in nodeJS, JavaScript, and jQuery. Any assistance would be greatly appreciated. ...

What is the best way to format and display a Jettison JSONObject in Jersey?

Is there a way to format JSON output nicely in Jersey with Jettison? Currently, I am sending a JSONObject (from Jettison) as the response entity in Jersey. Is there an option available to control whether the output is neatly formatted or not? I am open t ...

sending the express application to the route modules

Currently, I am developing an express 4 api server with no front end code. Rather than structuring my project based on file types such as routes and models, I have decided to organize it around the business logic of the project. For example, within my Use ...

Tips for including a variable in formData and the steps for implementing it in an ajax procedure

<input type='file' name='inpfile' id='inpfile' accept='image/*' hidden> javascript code var clicked; $('#btnplusa').click(function(){ clicked = 'a'; $('#inpfile').click ...

Is there a way to modify the parent component's state and pass it down to the child component as a prop efficiently?

I am facing an issue with a parent component that sets the score counter and passes it to the child component. There is a function in the parent component called resetBoard() which should reset the score counter back to 0 when triggered by a button click ...

Store text in a table format in your local storage

I need help figuring out how to save product and price information to local storage when an "add to cart" button is pressed. Can someone provide guidance on how to do this? Here is the code I currently have: body> <!-- Header--> ...

Repair the navigation bar once it reaches the top of the screen using ReactJS

I have a webpage that contains specific content followed by a bar with tabs. My goal is to have this bar stay fixed at the top of the screen once it reaches that position while scrolling down, and only allow the content below the fixed bar to continue scro ...

What is the best way to calculate the sum of table data with a specific class using jQuery?

If I had a table like this: <table class="table questions"> <tr> <td class="someClass">Some data</td> <td class="someOtherclass">Some data</td> </tr> <tr> <td class="s ...

How can I retrieve the index of an element within a 2D array using JavaScript when the array is displayed on a webpage?

https://i.stack.imgur.com/GHx9p.png I am currently working on developing an Othello game board within an HTML page using Angular. The board itself is constructed from a 2D number array which I then display using the <table> tag on the webpage. Below ...

Locate the child element that has a particular class assigned to it

I need help writing a code to search through all children elements in order to find a div with a specific class. Unfortunately, the DIV I am looking for does not have an ID. Below is the sample HTML that I will be working with: <div class="outerBUB ...

A common inquiry regarding Vue: How to effectively incorporate fullpage.js wrapper with additional functionalities

Having recently delved into Vue, I am currently tackling a project that involves the Fullpage.js Vue wrapper. While I have successfully implemented the Fullpage functionality, integrating additional features like an animation-on-scroll function has proven ...

Encountered an error when attempting to load resource: net::ERR_CERT_AUTHORITY_INVALID following deployment on Vercel

I recently deployed a chatUI-app on Vercel that fetches chats from an API located at "http://3.111.128.67/assignment/chat?page=0" While the app worked perfectly in development, I encountered an issue after deploying it on Vercel where it ...

Tips for arranging div elements in a grid-like matrix layout

I am facing a challenge in arranging multiple rectangular divs into a grid structure with 10 columns and 10 rows. The CSS styles for the top, bottom, left, or right positions must be in percentages to accommodate zoom in and out functionality without overl ...

Authenticate through navigation on an alternate component

I am in the process of developing a user interface that includes a side navigation and header bar. However, if the user is not logged in, I wish to redirect them to the login page. The primary component structure is as follows: class App extends Componen ...