-2

I have a question regarding array. I have a JSON output passing from PHP. My output is like below:

[{"Month":"Value Transactions"},{"6":"0.70"},{"7":"10.92"},{"8":"5.60"},{"9":"1.70"}]

I know maybe my question is duplicated. But I already find the solution but can't find it. I need the above JSON to be convert like below using javascript:

[ ["Month", "Value Transactions"], [6, 0.70], [7, 10.92], [8, 5.60], [9, 1.70] ]

How can I achieve this. Please help and thank you.

softboxkid
  • 877
  • 6
  • 13
  • 31
  • The posted question does not appear to include any attempt at all to solve the problem. Stack Overflow expects you to [try to solve your own problem first](https://meta.stackoverflow.com/questions/261592/), as your attempts help us to better understand what you want. Please edit the question to show what you've tried, so as to illustrate a specific roadblock you're running into in a [MCVE]. For more information, please see [ask] and take the [tour]. – CertainPerformance Sep 14 '19 at 11:00
  • Seems like you want to get the entries of each object: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries – Nick Parsons Sep 14 '19 at 11:03
  • For one you can use `JSON_NUMERIC_CHECK` in `json_encode` to not output numbers as strings. Can you change the PHP? Or is it fixed? –  Sep 14 '19 at 11:04
  • thank you for your answer. but i don't know how to do that. can you please give the sample code. I am beginner in Javascript – softboxkid Sep 14 '19 at 11:05
  • Possible duplicate of [From an array of objects, extract value of a property as array](https://stackoverflow.com/questions/19590865/from-an-array-of-objects-extract-value-of-a-property-as-array) – Mihail Minkov Sep 14 '19 at 18:48

1 Answers1

2

Using Object.entries. Note: coercing the number strings to a float will drop any extraneous zeros.

const data = [{"Month":"Value Transactions"},{"6":"0.70"},{"7":"10.92"},{"8":"5.60"},{"9":"1.70"}];

// If the parsed value is not a number return the value
// otherwise coerce it to an number
const getValue = (v) => Number.isNaN(parseFloat(v)) ? v : +v;

// `map` over the array objects
const out = data.map(obj => {

  // Extract the key and values from each object
  const [[ key, val ]] = Object.entries(obj);

  // Return an array with the correct values/types
  return [ getValue(key), getValue(val) ];
});

console.log(out);

Further reading:

Andy
  • 61,948
  • 13
  • 68
  • 95
  • Sir OP wants `0.70` and in your code it only `0.7` . I know that zero doesn't matter but then too look at your code sir . – Pushprajsinh Chudasama Sep 14 '19 at 11:37
  • It's clear he wants floating point numbers. Losing those zeros is the side effect of that. fwiw I wasn't the one who downvoted your answer. – Andy Sep 14 '19 at 11:38