Converting JavaScript object with numeric keys into array - javascript

I have an object like this coming back as a JSON response from the server:
{
"0": "1",
"1": "2",
"2": "3",
"3": "4"
}
I want to convert it into a JavaScript array like this:
["1","2","3","4"]
Is there a best way to do this? Wherever I am reading, people are using complex logic using loops. So are there alternative methods to doing this?

It's actually very straight forward with jQuery's $.map
var arr = $.map(obj, function(el) { return el });
FIDDLE
and almost as easy without jQuery as well, converting the keys to an array and then mapping back the values with Array.map
var arr = Object.keys(obj).map(function(k) { return obj[k] });
FIDDLE
That's assuming it's already parsed as a javascript object, and isn't actually JSON, which is a string format, in that case a run through JSON.parse would be necessary as well.
In ES2015 there's Object.values to the rescue, which makes this a breeze
var arr = Object.values(obj);

var json = '{"0":"1","1":"2","2":"3","3":"4"}';
var parsed = JSON.parse(json);
var arr = [];
for (var x in parsed) {
arr.push(parsed[x]);
}
console.log(arr)
Hope this is what you're after!

You simply do it like
var data = {
"0": "1",
"1": "2",
"2": "3",
"3": "4"
};
var arr = [];
for (var prop in data) {
arr.push(data[prop]);
}
console.log(arr);
DEMO

There is nothing like a "JSON object" - JSON is a serialization notation.
If you want to transform your javascript object to a javascript array, either you write your own loop [which would not be that complex!], or you rely on underscore.js _.toArray() method:
var obj = {"0":"1","1":"2","2":"3","3":"4"};
var yourArray = _(obj).toArray();

Nothing hard here. Loop over your object elements and assign them to the array
var obj = {"0":"1","1":"2","2":"3","3":"4"};
var arr = [];
for (elem in obj) {
arr.push(obj[elem]);
}
http://jsfiddle.net/Qq2aM/

var JsonObj = {
"0": "1",
"1": "2",
"2": "3",
"3": "4"
};
var array = [];
for (var i in JsonObj) {
if (JsonObj.hasOwnProperty(i) && !isNaN(+i)) {
array[+i] = JsonObj[i];
}
}
console.log(array)
DEMO

Try this:
var newArr = [];
$.each(JSONObject.results.bindings, function(i, obj) {
newArr.push([obj.value]);
});

You can use Object.assign() with an empty array literal [] as the target:
const input = {
"0": "1",
"1": "2",
"2": "3",
"3": "4"
}
const output = Object.assign([], input)
console.log(output)
If you check the polyfill, Object.assign(target, ...sources) just copies all the enumerable own properties from the source objects to a target object. If the target is an array, it will add the numerical keys to the array literal and return that target array object.

var obj = {"0":"1","1":"2","2":"3","3":"4"};
var vals = Object.values(obj);
console.log(vals); //["1", "2", "3", "4"]
Another alternative to the question
var vals = Object.values(JSON.parse(obj)); //where json needs to be parsed

Using raw javascript, suppose you have:
var j = {0: "1", 1: "2", 2: "3", 3: "4"};
You could get the values with:
Object.keys(j).map(function(_) { return j[_]; })
Output:
["1", "2", "3", "4"]

Not sure what I am missing here but simply trying the below code does the work. Am I missing anything here?
https://jsfiddle.net/vatsalpande/w3ew5bhq/
$(document).ready(function(){
var json = {
"code" :"1",
"data" : {
"0" : {"id":"1","score":"44"},
"1" : {"id":"1","score":"44"}
}
};
createUpdatedJson();
function createUpdatedJson(){
var updatedJson = json;
updatedJson.data = [updatedJson.data];
$('#jsondata').html(JSON.stringify(updatedJson));
console.log(JSON.stringify(updatedJson));
}
})

Assuming your have a value like the following
var obj = {"0":"1","1":"2","2":"3","3":"4"};
Then you can turn this into a javascript array using the following
var arr = [];
json = JSON.stringify(eval('(' + obj + ')')); //convert to json string
arr = $.parseJSON(json); //convert to javascript array
This works for converting json into multi-diminsional javascript arrays as well.
None of the other methods on this page seemed to work completely for me when working with php json-encoded strings except the method I am mentioning herein.

Here is an example of how you could get an array of objects and then sort the array.
function osort(obj)
{ // map the object to an array [key, obj[key]]
return Object.keys(obj).map(function(key) { return [key, obj[key]] }).sort(
function (keya, keyb)
{ // sort(from largest to smallest)
return keyb[1] - keya[1];
}
);
}

This is best solution. I think so.
Object.keys(obj).map(function(k){return {key: k, value: obj[k]}})

The accepted solution expects the keys start from 0 and are continuous - it gets the values into the array, but looses the indexes on the way.
Use this if your "object with numerical keys" does not fulfill those stricter assumptions.
//let sourceObject = ...
let destinationArray = [];
Object.keys(sourceObject).forEach(k => destinationArray[k] = sourceObject[k]);

var data = [];
data = {{ jdata|safe }}; //parse through js
var i = 0 ;
for (i=0;i<data.length;i++){
data[i] = data[i].value;
}

You can convert json Object into Array & String using PHP.
$data='{"resultList":[{"id":"1839","displayName":"Analytics","subLine":""},{"id":"1015","displayName":"Automation","subLine":""},{"id":"1084","displayName":"Aviation","subLine":""},{"id":"554","displayName":"Apparel","subLine":""},{"id":"875","displayName":"Aerospace","subLine":""},{"id":"1990","displayName":"Account Reconciliation","subLine":""},{"id":"3657","displayName":"Android","subLine":""},{"id":"1262","displayName":"Apache","subLine":""},{"id":"1440","displayName":"Acting","subLine":""},{"id":"710","displayName":"Aircraft","subLine":""},{"id":"12187","displayName":"AAC","subLine":""}, {"id":"20365","displayName":"AAT","subLine":""}, {"id":"7849","displayName":"AAP","subLine":""}, {"id":"20511","displayName":"AACR2","subLine":""}, {"id":"28585","displayName":"AASHTO","subLine":""}, {"id":"45191","displayName":"AAMS","subLine":""}]}';
$b=json_decode($data);
$i=0;
while($b->{'resultList'}[$i])
{
print_r($b->{'resultList'}[$i]->{'displayName'});
echo "<br />";
$i++;
}

Related

Javascript loop through object of many objects

I have a string JSON http response.
{
"1537988400000": {
"6495": ["18", "29"],
"6490": ["34", "40"],
"6500": ["7", "213"],
"6505": ["13", "17"]
},
"1537992000000": {
"6490": ["45", "87"],
"6485": ["15", "4"],
"6495": ["78", "222"],
"6500": ["176", "141"],
"6505": ["64", "94"],
"6510": ["7", "53"],
"6515": ["0", "1"]
}
}
I want to parse it to a JavaScript object. The object must be structured so that I could get the numbers from the arrays. For instance, I choose "1537992000000" -> "6495" -> [1] and get '222'.
Here is my code:
var resp = this.responseText; // JSON string
var object = JSON.parse(resp);
for (var obj in object) {
for (var a in obj) {
alert(a[0]); // should return the first number in the array of an object
}
}
The problem is that it doesn't return numbers. It sends something like 0,1..9,10.. (Seems like these are the indexes of each property's properties)
Your JSON pase logic is fine, you have mistaken here, obj is key
for (var obj in object)
The object must be structured so that I could get the numbers from the arrays.
var json={"1537988400000":{"6495":["18","29"],"6490":["34","40"],"6500":["7","213"],"6505":["13","17"]},"1537992000000":{"6490":["45","87"],"6485":["15","4"],"6495":["78","222"],"6500":["176","141"],"6505":["64","94"],"6510":["7","53"],"6515":["0","1"]}}
for(var i in json){
for(var j in json[i]){
console.log(json[i][j]);
}
}
for(var a in obj){
Seems like these are the indexes of each property's properties
Yes. That is what in does. Use of to loop over values.
var data = '{"1537988400000":{"6495":["18","29"],"6490":["34","40"],"6500":["7","213"],"6505":["13","17"]},"1537992000000":{"6490":["45","87"],"6485":["15","4"],"6495":["78","222"],"6500":["176","141"],"6505":["64","94"],"6510":["7","53"],"6515":["0","1"]}}';
data = JSON.parse(data);
for (var obj in data) {
for (var a in data[obj]) {
console.log(data[obj][a]);
}
}

JS: Finding next key in json

I have the following json:
{0: "2", 1: "2", $$hashKey: "object:35", undefined: "1"}
Currently I am trying to get its key-value with the below code:
var data = JSON.stringify(row);
var result = $.parseJSON(data);
$.each(result, function (k, v) {
//display the key and value pair
console.log(k, v);
});
The above code works fine and I can get my key-value from it.
Now what I am trying to get is the next key-value pairs within the $.each loop.
For example if in the loop the current key is "0" I want to get the next key "1" in the same call itself. If in the loop the current key is "1" I want to get the next key "$$hashKey" along with their values.
Is it possible to do so? I am open to code changes above if required.
You can use Object.keys to get the keys to an array, then run through it with a forEach to have access to the keys index. Important to note that objects are unordered, so your key order one time may differ from the next time:
var keys = Object.keys(obj);
keys.forEach(function(key, index) {
var nextIndex = index + 1;
if (nextIndex === keys.length) return; //out of bounds
var nextKey = keys[nextIndex];
});
Edit: As pointed out by the comments - if you want the keys in the same order each time, call .sort() on your keys array with your desired sort logic.
Understanding now that the goal is to retrieve keys in the order they appear in JSON, a couple of thoughts:
(1) if you control the source of the object ("row" in the OP code), don't represent it as an object. instead use an array of key-value pairs: [[0, "2"], [1, "2"], [$$hashKey, "object:35"], [undefined, "1"]].
otherwise, (2) roll your own JSON parser that returns an array of key-value pairs for an object. This post looks to be a sensible start. Or, you can vastly simplify the task if you are able to make certain assumptions about the values, for example, say you know that all values are strings...
// parse a string representing an object, returning an array of key-value pairs.
// assumes values are strings that do not contain commas or colons
function myProbablyNegligentlySimpleJSONParse(string) {
let trimmed = string.trim().slice(1, -1);
let components = trimmed.split(',');
return components.map(kvString => {
let kv = kvString.split(':');
return [ kv[0].trim(), kv[1].trim() ];
});
}
forEach passes the current index to the iterator function, so that int can be used to look ahead or behind in the iteration.
var data = '{0: "2", 1: "2", $$hashKey: "object:35", undefined: "1"}';
let result = myProbablyNegligentlySimpleJSONParse(data);
result.forEach(function (pair, index) {
let [k, v] = pair; // now k and v are your key and value
console.log(`key is ${k} value is ${v}`)
if (index < result.length-1) {
let [nextK, nextV] = result[index+1];
console.log(`next key is ${nextK} next value is ${nextV}`);
}
});
You could turn your object into an iterable and which will return the next [key, value] pair each time you call next on the iterator:
function makeIterable(o) {
o[Symbol.iterator] = () => {
var keys = Object.keys(o);
var i = 0;
return {
next() {
var done = false;
var value = [keys[i + 1], o[keys[i + 1]]];
if (i >= (keys.length - 1)) {
done = true;
}
i++;
return {
value,
done
}
}
};
}
}
var jsonStr = '{ "0": "2", "1": "2", "$$hashKey": "object:35", "undefined": "1" }';
var obj = JSON.parse(jsonStr);
makeIterable(obj);
var itr = obj[Symbol.iterator]();
while (true) {
var item = itr.next();
if (item.done) {
break;
}
console.log(item.value);
}

merge two object and rename same property

I have two object which contain some similar properties. I want to merge those two object in one object and also want to rename the similar properties from both objects.
var selectedEntity = {"UsageS":"123","DateS":"2016","IsEstimeated":"True"};
var ComapareEntity = {"UsageC":"124","DateC":"2015","IsEstimeated":"False"}
Result = {"UsageS":"123","DateS":"2016","IsEstimeatedS":"True","UsageC":"124","DateC":"2015","IsEstimeatedC":"False"};
Please suggest some solution using lodash.
Try to put these two objects in a json array, so that index can used to name duplicate keys
var selectedEntity = {
"UsageS": "123",
"DateS": "2016",
"IsEstimeated": "True"
};
var ComapareEntity = {
"UsageC": "124",
"DateC": "2015",
"IsEstimeated": "False"
}
var toLoopArray = [selectedEntity, ComapareEntity]
var resultantObject = {};
toLoopArray.forEach(function(item, index) {
for (var keys in item) {
if (!(resultantObject.hasOwnProperty(keys))) {
resultantObject[keys] = item[keys]
} else {
resultantObject[keys + index] = item[keys]
}
}
})
console.log(resultantObject)
JSFIDDLE

How to parse a string into an array

If a have a string in this format:
$parsethis = 'string[1][2]';
How do I parse it so my result is an array like:
$parsed = ['string', 1 , 2]
I think REGEX is the way to go here, in compiination with the Arrays split method.
var array = $parsed.split(/\]\[|\[|\]/);
console.log(array) results in
Array [ "string", "1", "2", "" ]
iam not very good at using regular expressions, but maybe this is leading you in the right direction.
You can do something like this:
var $parsethis = 'string[1][2]';
var arr = $parsethis.replace(/\]/g,'').split('[');
//arr = ["string", "1", "2"]
alert(arr); //alerts "string,1,2"
The arr array will be all strings, though. Based on the question, I do not know how you will be using the results.
You can get an array from that string using str.split(), and then cleaning it up with str.replace().
var parsed = parsethis.split('[');
console.log(parsed); // ["string", "1]", "2]"]
for(var i = 0; i++; i<parsed.length){
parsed[i] = parsed[i].replace(']','');
}
console.log(parsed); // ["string", "1", "2"]

javascript: How to get highest layer of json object as array?

With an array of objects in a form like this:
[
{
1429={
{
8766={...},
8483={...},
7345={...}
}
}
},
{
9041={...}
}
]
how could i get back an array like this?:
[1429, 9041]
If the array of objects would be in another structure this code would work:
var obj = {
"5": "some",
"8": "thing"
};
var keys = $.map(obj, function (value, key) {
return key;
});
console.log(keys);
That would return [5, 8]. But in my example it just would return the indexes [0,1]
Even if I wouldn't know the depth of the object - is it possible to get the values on that level? I dont need the indexes, I need those values. I couldn't find anything about it so far. Any tips for me maybe?
P.S.: I know that i could work out something with these keys and a loop, but I'm just asking for a simplier way to do it.
Regards
you are looking for the keys in a json object, you can get them this way:
Object.keys(obj);
for the object example:
var obj = {
"5": "some",
"8": "thing"
};
you will get:
["5","8"]
for an array of object of this type:
var arrayObject = [{},{},{}];
you can use a map and get the keys:
var keys = arrayObject.map(function(k){
return Object.keys(k);
});
keys is an array of arrays of keys. Example, for the following object (similar to your data structure):
var l= [
{
1429:{
8766: "test",
8483:"test",
7345: "test"
}
},
{
9041: "test"
}
];
you will get:
[["1429"],["9041"]]
apply concat and you will get what you are looking for. Here how to apply concat in the case of multiple arrays.
var arrayOfKeys = [].concat.apply([], keys);
now you will get:
["1429","9041"];
In your specific case you could use
var keys = [];
root.forEach(function(v) { keys = keys.concat(Object.keys(v)); });
If instead you have a tree of arrays and you want the keys of all other objects instead (but not recursing into objects) then a simple recursive function would do it:
function topKeys(x) {
if (x && x.constructor === Array) {
var result = [];
x.forEach(function(item) {
result = result.concat(topKeys(item));
});
return result;
} else if (typeof x === "object") {
return Object.keys(x);
} else {
return [];
}
}

Categories