"Converting a JSON object into a JSON array using JavaScript: A step-by-step

My JSON object:

{Yana: 1, Pirelli: 2, Good Year: 1}

The results I anticipate:

series: [
         {name: 'Yana', data: [1]},
         {name: 'Pirelli', data: [5]},
         {name: 'Good year', data: [5]}
        ]

Answer №1

Using Object.entries to simplify the process:

var users = {"John": 25, "Mary": 30, "Joe": 22};
var transformedData = Object.entries(users).map(([name, age]) => ({name, age}));
console.log (transformedData);

Answer №2

To iterate through the keys of an object and create a new array based on its values, you can utilize the combination of forEach() and Object.keys():

var data = {"John":1,"Doe":2,"Smith":1};
var newArray = [];
Object.keys(data).forEach(key => newArray.push({name: key, value:[data[key]]}));
console.log(newArray);

Answer №3

What do you think of this approach?

let cars = {"Toyota": 4, "Honda": 3, "Ford": 5};

Object.keys(cars).map(brand => {
    return {name: brand, quantity: [cars[brand]]};
})

The Object.keys method is used to extract the keys from the cars object, allowing us to loop through them using map. With this technique, we can easily create the desired output array structure.

Answer №4

The provided input does not conform to proper JSON syntax. Here is how your data should look in JSON format:

{"Yana": 1, "Pirelli": 2, "Good Year": 1}

If you have this data stored as a string, the first step is to parse it into a JavaScript object:

const jsonData = '{"Yana": 1, "Pirelli": 2, "Good Year": 1}'
const obj = JSON.parse(jsonData);

// Extract all keys from the object:
const brands = Object.keys(obj);

// Next, construct a new object with the desired properties:
const result = brands.map(brand => {
  return {
    name: brand,
    data: obj[brand]
  };
})

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

validate that the input contains only numbers within the range of 5 to 60

I need to validate inputted numbers within the range of 5-60. <div class="col-md-3"> <input type="text" name="gd_time" id="gd_time" placeholder="Enter a number between 5 and 60 " class="form-control"> </div> The script I have attemp ...

Issue with AngularJS directives - encountering a problem with the property 'compile' being undefined

Just starting out with AngularJS and attempting to make a basic directive. Unfortunately, the code is throwing a TypeError: Cannot read property 'compile' of undefined. Any advice or suggestions would be greatly welcomed. JS var xx = angular.mo ...

Deactivating the click event for a personalized checkbox's label in Bootstrap

Greetings, <div class="form-check"><input class="form-check-input" type="checkbox" value="" id="defaultCheck1"><label class="form-check-label" for="defaultCheck1">Default checkbox</label></div> Is there a way to disable the ...

Commencing a download using command line inputs

In continuation to the discussion on this topic, I am looking for a solution to embed a download link in an HTML page after a successful purchase via PayPal. The page will include various "tokens" such as "PayerID", and I am exploring the possibility of ...

dynamically display elements within aframe based on specific conditions

In my aframe scene, there are three icosahedrons, a complex particle system, and a cursor that fuses on objects within the scene. The performance of the scene is affected when the particles are visible because the cursor attempts to fuse with every particl ...

Transformation effect when hovering over an SVG polygon as it transitions between two states

const createTransitionEffect = (navLI, startCoord, endCoord) => { const changeRate = 0.1; let currentY = startCoord; const animateChange = () => { if (currentY !== endCoord) { currentY += (endCoord - startCoord) * cha ...

Error: The function "this.state.data.map" is not defined in ReactJS

class Home extends Component { constructor(props) { super(props); this.state = { data: [], isLoaded: false, }; } componentDidMount() { fetch("https://reqres.in/api/users?page=2") .then((res) => res.json ...

I require the json data to be divided into smaller segments

I have a JSON file that I need to modify by splitting the "Vs" column into two separate columns. I want to create new columns named team 1 and team 2 by splitting the data after 'vs'. Can anyone guide me on how to achieve this using a python scri ...

Count of daily features in JavaScript

Suppose there is a json document structured as follows: { "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": { "time": 1438342780, "title": "Iran's foreign minister calls for world's ...

Incrementing the vector element with a counter as we iterate through the dataframe

Currently getting the hang of R programming. I'm currently immersed in a project that involves analyzing a dataset with columns for PMID, MESH terms (MH), and year (EDAT_Year). My objective is to create a vector that tracks the occurrence of a specifi ...

Is there a way to search for the keyword "/test/" within a lengthy string using Regular Expressions?

When faced with a string structured like this: const myString = /example/category/modify?itemID=someID&type=number How can I efficiently extract the segment "/category/" by employing: const subSegment = myString.match(...); My framework of choice i ...

Benefits of Utilizing Object.create

Unlike the referenced question, this code snippet is sourced from the book "JavaScript: The Definitive Guide". It introduces an inherit method that applies Object.create if available, but falls back to traditional JavaScript inheritance when it's not. ...

Exploring intricate API JSON data recursively with Python

This function takes a key as an input and searches for that key in the entire JSON data, returning a list of key-value pairs associated with that key. While this method works well for standard key-value pairs like {'key':'some value'}, ...

What is the best way to conceal specific HTML content without the use of <noscript> tags when JavaScript is turned off?

<html> <head> <script type="text/javascript"> // jquery and javascript functions </script> </head> <body> <fancy-jquery-ajaxy-html-section> </fancy-jquer ...

A JSON string transformed into a JSON value

Can a JSON string be used as a value within another JSON structure? Please provide a valid JSON string as a value of a JSON element. Here is an example of what I am looking for: { "numberOfBlocks": 2, "1": { "items": [ { "Id": "11 ...

Using MongoDB map-reduce with Node.js: Incorporating intricate modules (along with their dependencies) into scopeObj

I am currently immersed in developing a complex map-reduce process for a mongodb database. To make the code more manageable, I have organized some intricate sections into modules that are then integrated into my map/reduce/finalize functions through my sco ...

Encountering TypeScript errors with React-Apollo when using GraphQL to pass props to a higher order component

I've encountered some challenges while attempting to link a React class component with my local Apollo cache data. Following the guidelines outlined here, I have run into issues where VSCode and Webpack are generating errors when I try to access data ...

Checkbox column within GridView allows users to select multiple items at once. To ensure only one item is selected at a

Currently, I am facing a challenge with dynamically binding a typed list to a GridView control within an asp.net page that is wrapped in an asp:UpdatePanel for Ajax functionality. One of the main requirements is that only one checkbox in the first column c ...

An issue occurred while making an HTTP PUT request to Shopify due to a problem with sending an array in the JSON request for

Here is a description of how to update the metafield of an existing article in Shopify using an http PUT response. For detailed API documentation on Articles, click here func UploadArticleListImg(client *http.Client, ArticleIDs []string, imageURL []string ...

React component still not updating, even though the props object has been modified

Despite the abundance of similar questions, I can assure you that this is a unique case related to props being an object. After thorough research, I have come to the realization that my issue remains unsolved: class CsvListDropdown extends Component { ...