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

Generate a compilation of products developed with the help of angularjs

I have a request to make a list of items using Directives and share them through controllers. Check out my code example on plunker: Code Example Below is the JavaScript code: var app = angular.module('app', []); app.controller("BrunchesCtrl", ...

conceal elements using the <option> class隐藏

Although it seems like a simple task, I'm struggling to make it work. I created a form where the user can select a month from a list using the tags: <select> <option> When the selection is changed, the class .gone from the day SELECT is ...

What is the best way to parse this JSON structure using restsharp in c#?

What is the best way to structure my classes in order to successfully deserialize the JSON data provided below? { "Bob": [{ "code": "Bob", "tier": 1 }, { "code": "Bob", "tier": 2 ...

Utilizing PostgreSQL to extract fields from jsonb data

I have implemented a generated column in PostgreSQL 12 that extracts data from a jsonb field (which contains either "public":true or "public":false). CREATE TABLE people ( ..., data jsonb, public boolean generated always as ((data ->> &a ...

Is there a way to trigger a function with ng-click in my AngularJS directive?

I am struggling to understand how to invoke a function from my directive using ng-click. Here is an example of my HTML: <div> <directive-name data="example"> <button class=btn btn-primary type="submit" ng-click="search()"> ...

Struggling to get a printout when parsing JSON in Swift

I'm a newcomer to Swift and I'm looking to retrieve some JSON data from the server using a URL. Despite trying several other solutions, none have worked for me. My goal is to extract and print the duration key (both text and value) from the array ...

Simplified jQuery function for multiple div mouseover operations

Uncertain about the accuracy of my title. Due to certain reasons, I need to assign different IDs for the class, as it only detects ID and not class when hovered over. Therefore, I have created a CSS version where the opacity of a specific div will change t ...

Getting the expanded row columns values in a RadGrid when using the onHierarchyExpanded event

Here is the code for my RadGrid: <telerik:RadGrid ID="ProductRanges_Grd" ShowHeaderWhenEmpty="true" runat="server" AutoGenerateColumns="false" Width="100%" Height="250px" ShowHeader="true" Visible="false" ...

Tips for including parameters in an array of values when using getStaticPaths

I'm trying to retrieve the slug value that corresponds with each number in the getStaticPaths for my page structure: /read/[slug]/[number]. The code I have is as follows: export async function getStaticPaths() { const slugs = await client.fetch( ...

Looking for a way to retrieve JSON data from an HTML page using JavaScript? Look no further

There is a page that sends me JSON data. You can make the request using the GET method: or using the POST method: argument --> unique_id=56d7fa82eddce6.56824464 I am attempting to retrieve this information within my mobile application created with I ...

Activate the 'li' element within the 'ul' whenever a 'ui-sref' link on the

I have been working on building a dashboard that consists of an abstract state called dashboard, with subdashboard as the immediate child state. Previously, clicking on user details would take the user to the dashboard.tables state. However, I encountered ...

Creating an Extjs model for a complex nested JSON structure

Take a look at this JSON structure { "id": 123, "name": "Ed", "orders": [ { "id": 50, "total": 100, "order_items": [ { "id": 20 ...

Uploading photos to Postgres through express/multer

Currently, I am using Postman to send images to a POST route through the Express library. However, when I retrieve the buffer of binary data, I am unable to process it accordingly. Will using body-parser resolve this issue? This is how I am uploading the ...

The jQuery AJAX call is successful in Firefox, but unfortunately, it is not working in Internet Explorer

I've encountered a perplexing issue with an AJAX call. It's functioning perfectly fine in Firefox, but for some reason, it's not working in IE. Curiously, when I include an alert() specifically for IE, I can see the returned content, but the ...

React checkbox remains checked even after uncheckingIs this revised version

I am currently working on a React application where I display an array of matches as a list of rows. Each row contains two athletes, and users can use checkboxes to predict the winner for each match. Only one athlete per row can be checked. To keep track o ...

Continuously replicate SVG horizontally without limit

In search of the perfect visual effect, I am eager to develop an infinite animation featuring a car moving horizontally with various landscape layers passing by in SVG format. Struggling to find a way to seamlessly repeat my SVG landscape layers along the ...

Validate forms using jQuery with the power of ajax

Is there a way to effectively check for the existence of a username? I want to increment a variable called "form_error" if the username already exists. If "form_errors" is greater than 0, I need the code to stop and return false. However, when I use an Aj ...

Utilize JavaScript to load images at random within a Qualtrics loop and merge block

I'm currently putting together a survey on qualtrics using a block with loop and merge functionality. I've encountered an issue where, after the first iteration, the images I'm loading through javascript start disappearing. Although I can br ...

"Techniques for incorporating a screen in Angular application (Switching between Edit and View modes) upon user interaction

We are currently working on a screen that requires the following development: This screen will have the following features: When clicking on a button, the fields should become editable. In the image provided, there is some repeated data, but in our case, ...

JavaScript - What is the best way to add the same object value into an array?

After spending a few hours trying to figure out how to manage JSON data structured like this: [ { "value": "Osteonecrosis", "Diagnosis_Code": "DIAG002", "NamaCategory": "Primary Category", "FK_Diagnosis_Content_ID": 2 }, { "value ...