Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Remove keys from json object

Example output from PHP:

{
    "RootName_0":{"Id":1,"ValId":1,"Value":"Colour","Text":"Blue"},
    "RootName_1":{"Id":1,"ValId":2,"Value":"Colour","Text":"Red"}
}

How can I use Backbone.js or jQuery to only have:

[
    {"Id":1,"ValId":1,"Value":"Colour","Text":"Blue"},
    {"Id":1,"ValId":2,"Value":"Colour","Text":"Red"}
]

If it's easier to use PHP to edit the JSON, then so be it.

like image 285
Nahydrin Avatar asked May 13 '26 19:05

Nahydrin


2 Answers

Well, in PHP it would be easy, just use array_values() on the initial array so that it 'forgets' the array indexes (which by the way, is what 'RootName_X' is called in your case:

$newvalue = array_values( (array)$value );
echo json_encode($newvalue);

In javascript, it's a bit trickier, but it would be on the lines of:

var newvalue = [];
for(var root in value)
   newvalue.push(value[root]);

The question title is was a bit confusing since these are certainly not tags.

like image 139
Christian Avatar answered May 16 '26 10:05

Christian


No need for jquery or Backbone:

var obj = {
    "RootName_0":{"Id":1,"ValId":1,"Value":"Colour","Text":"Blue"},
    "RootName_1":{"Id":1,"ValId":2,"Value":"Colour","Text":"Red"}
};
var colors = [];

for(var key in obj){
   colors.push(obj[key]);
};

The value you want is now in the colors array.

like image 44
driangle Avatar answered May 16 '26 08:05

driangle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!