transform a JSON object into a new format

I am working with a JSON object that looks like this:

 [
  {
    "AF28110": 33456.75,
    "AF27989": 13297.26
  }
]

My goal is to convert it into the following format:

[ 
 { "name": "AF28110", "price": 33456.75},
 { "name": "AF27989", "price": 13297.26}
]

I have attempted to use various methods like .map() to achieve this transformation, but I have been unsuccessful so far.

If anyone has any insights or ideas on how to accomplish this task, your help would be greatly appreciated! Thank you.

Answer №1

Give this code a shot:

const result = [];
inputs.forEach(item => Object.keys(item).forEach(key => result.push({property: key, value: item[key]})))

Object.keys extracts the keys from each object, allowing you to create a separate array item for each property.

Answer №2

Utilizing the map method:

const items = [
  {
    "XV37293": 54982.16,
    "DN93842": 20371.43
  }
]

const result = Object.keys(items[0]).map(item => {
  return { product: item, price: items[0][item] };
});

console.log(result)

Answer №3

One way to achieve this is by utilizing concat, Object.keys, and map. By iterating through each item in the array, extracting keys from the object, and mapping each key to the desired name/price object, you can create a new array with the transformed data. Finally, flatten the resulting array using concat for a clean output.

For example:

const arr = [{
  "AF28110": 33456.75,
  "AF27989": 13297.26
}]

const result = [].concat(...arr.map(o => Object.keys(o).map(k => ({name: k, price: o[k]})))
console.log(result);

Answer №4

If you have a collection of various items in an array, the reduce method comes in handy.

let arr = [
  {"item1": 23.50,"item2": 10.75},
  {"item3": 35.20,"item4": 15.60}
];

let result = arr.reduce((collection, value) => collection.concat(Object.entries(value).map(obj => {return {name: obj[0], price: obj[1]}})), []);

console.log(result);

Answer №5

Give this a shot,

let data = '[{"AF28110": 33456.75,"AF27989": 13297.26}]';
let jsonData = JSON.parse(data);
let finalResult = [];
for (x = 0; x < jsonData.length; x++) {
 let properties = Object.keys(jsonData[x]);
 for (y = 0; y < properties.length; y++){
    finalResult[y] = '{ "name":' +properties[y] + ', "price":' + jsonData[x][properties[y]]+'}';
 } 
}
console.log(finalResult);

Many thanks.

Answer №6

Effective methods for achieving the desired outcome:

  • Utilizing the Object.keys function :

var data = [
  {
    "AF28110": 33456.75,
    "AF27989": 13297.26
  }
];

var result = Object.keys(data[0]).map(key => {
  return {"name": key, "value": data[0][key] };
});

console.log(result);

  • Using the Object.getOwnPropertyNames approach :

var data = [
  {
    "AF28110": 33456.75,
    "AF27989": 13297.26
  }
];

var result = Object.getOwnPropertyNames(data[0]).map(key => {
  return {"name": key, "value": data[0][key] };
});

console.log(result);

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

Encountering a d3.js runtime issue following the transition to Angular 8

I've been experimenting with upgrading my Angular 6 application to Angular 8. It compiles fine, but I'm facing a runtime error as soon as it runs: "d3.js:8 Uncaught TypeError: Cannot read property 'document' of undefined". The specific ...

Search for objects in the array that have the same name, and then combine the values of those matching

I've done some research on various platforms, but haven't come across a solution to my specific issue. I'm looking to extract objects from an array and group them by their names in order to calculate the total hours for each matching object. ...

Personalized styling in material-ui v4.9.0

I recently updated the Material UI version in my project from 0.20 to v4.9. I have successfully changed all the imports to @material-ui/core and my app is compiling without any issues. However, I am facing a problem with the styling. Previously, I did not ...

"Encountering a HSSFCell error when trying to read null

Struggling with creating an Excel-to-JSON converter for a volunteer project, I keep encountering perplexing errors that resist correction. The error message goes as follows: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at bin.pars ...

Creating nested objects from nested arrays in PHP is a simple task that involves iterating through the

Here is a code snippet that initializes a config: $this->config = array( 'users' => array( array('name' => 'admin', 'password' => $password ) ...

Is drag and drop functionality in Safari on iOS automatically enabled, or will I need to write code to implement it myself?

Is there a way to detect when an HTML element is being dragged and dropped specifically for Safari events? For drag and drop functionality on Safari iPad, do I need to manually detect mousemove events on HTML elements and update their positions as the mou ...

Leveraging symbols as object key type in TypeScript

I am attempting to create an object with a symbol as the key type, following MDN's guidance: A symbol value may be used as an identifier for object properties [...] However, when trying to use it as the key property type: type obj = { [key: s ...

I'm having trouble getting NextJS dynamic routes to function properly on my local server

src/app/user/[username].js [username].js content: import { useRouter } from 'next/router' export default function User() { const router = useRouter() return ( <p> {router.query.username} </p> ); } Upon visiting ...

Using styled components but lacking the ability to use the className property

Currently, I am working with React and styled components and utilizing a third-party component called IntlTelInput. Below is a snippet of my code: const StyledIntlTelInput = styled(IntlTelInput)` background: blue; `; export default function PhoneNu ...

Menu with a slider featuring three different choices

I am currently working on creating a box with a title and two arrows positioned to the left and right of the title. The goal is for the box to fade out when either arrow is clicked, and then fade in with the next option. I have a similar setup already impl ...

A messaging application powered by socket.io and the Express JS framework

I am currently learning Node.js and I am encountering an issue with using socket.id to identify logged in users on the client side using their email id and password. The verification process happens on the server side, and if successful, the user's so ...

A method in JQuery to replace an input with a select element is by using the replace

I have multiple input fields with pre-existing values. My goal is to replace these inputs with select dropdowns that have the same options while retaining the original values. Here is the current HTML structure: <span id="span1"> <input type=" ...

In order to dismiss the popup message in the component.ts file within Angular 4, I must figure

Currently in my component.html, I have a popup message with opening and closing functionality implemented in html. However, I now need the close functionality to be moved to a method. <ng-template #content let-c="close" let-d="dismiss"> < ...

Error encountered when attempting to send ajax request to specified http endpoint using Cordova version 10

I've been struggling to successfully send JSON data to an HTTP URL (although I was able to successfully send the same data to an HTTPS URL). These are my current settings: config.xml <access origin="*" /> <allow-intent href="ht ...

Creating the ideal object for a response: top recommendations

I have a REST server powered by Spring framework. Numerous requests are received where one of the parameters is fields. This parameter represents a set of fields that the server should include in the response. For example: /?fields=[id,name], and the serve ...

"Error message: Antd datepicker is throwing an error stating that date.clone/date.load is not a

I am working on a React app that has a checkbox to disable a datepicker. However, when I use the checkbox to disable it, I am unable to select any date. If I remove the checkbox and its function, there is no error. Currently, the error message I am getting ...

Sending requests across domains from HTTPS to HTTP with callback functionality, and reversing the process

Prior to our conversation, I had created it using Flash. I uploaded a special file (crossdomain.xml) on the server side (https), while the Flash component was placed on the http server. Although they belong to different domains on the https and http serv ...

How to make a GET request to a Node server using Angular

I am currently running a node server on port 8000 app.get('/historical/:days' ,(req,res,next){..}) My question is how to send a request from an Angular app (running on port 4200) in the browser to this node server. Below is my attempt: makeReq ...

Encountering errors while attempting to render MUI components in jsdom using react testing library within a mocha test

Due to the lack of maintenance and support for React 18+ in enzyme, I am faced with the task of migrating over 1750 unit tests to work with react-testing-library and global-jsdom. This migration is necessary so that our application can continue running on ...

Introducing the latest issue: "Annotation Not Found" bug detected in flowjs version 0.54.0!

Following the update to flow 0.54.0, the code snippet below is encountering an issue: function runKarmaTest() { const KARMA_CONFIG = {}; return new Promise(function (resolve, reject) { new karma.Server(KARMA_CONFIG, function (exitCode) { ...