var arr=[];
arr['first']='val1';
arr['second']='val2';
var json=JSON.stringify(arr);
var obj=JSON.parse(json); //obj is array
Can I return object {"first":"val1","second":"val2"} ?
P.S.: I read Convert Array to Object topic
I'm interested in this way of the function
If somebody has abused arrays like that, JSON does not help you. It will only serialize the numeric indices of Array objects, nothing else. Copy the properties by hand:
var obj = {};
for (var prop in arr)
if (arr.hasOwnProperty(prop)) // don't copy enumerables from Array.prototype
obj[prop] = arr[prop];
console.log(obj); // {"first":"val1","second":"val2"}
You shouldn't use an array to represent this:
Do this instead:
var obj = {first:"val1",second:"val2"};
Just define the object directly . Stringify and parsing is not necessary
Related
i have this array
"[{\"category_id\":\"2\",\"category_name\":\"Fun\"},
{\"category_id\":\"3\",\"category_name\":\"Science\"},
{\"category_id\":\"4\",\"category_name\":\"Art\"},
{\"category_id\":\"5\",\"category_name\":\"Nature\"},...]"
i want to output this in user readable format
It’s not an array. It’s a string.
Perhaps you mean
var x = "[{\"category_id\":\"2\",\"category_name\":\"Fun\"},{\"category_id\":\"3\",\"category_name\":\"Science\"},{\"category_id\":\"4\",\"category_name\":\"Art\"},{\"category_id\":\"5\",\"category_name\":\"Nature\"}]"
console.log(JSON.stringify(JSON.parse(x)))
Try below code.
var obj = "[{\"category_id\":\"2\",\"category_name\":\"Fun\"},{\"category_id\":\"3\",\"category_name\":\"Science\"},{\"category_id\":\"4\",\"category_name\":\"Art\"},{\"category_id\":\"5\",\"category_name\":\"Nature\"},...]";
obj = obj.replace(/\\/g, '');
console.log(obj);
window.onload = function() {
var arr = new Array;
var jsonObj = {
"123": "234"
};
arr['v'] = "234";
arr[0] = jsonObj;
arr[1] = jsonObj;
console.log(JSON.stringify(arr));
}
The above code result is :
[{"123":"234"},{"123":"234"}]
I don't know why the arr['v'] disappeared?
Object and Array are not parsed to JSON the same way.
an Array will only include the numeric keys, and an Object will include all of its keys:
var Arr = [], Obj ={};
Arr[0] = Obj[0] = 'a';
Arr[1] = Obj[2] = 'b';
Arr['key'] = Obj['key'] = 'c';
console.log(JSON.stringify(Arr));
console.log(JSON.stringify(Obj));
so in your case, you could simply use an Onject instead of an array:
var arr = new Object;
var jsonObj = {"123":"234"};
arr['v'] = "234";
arr[0] = jsonObj;
arr[1] = jsonObj;
console.log(JSON.stringify(arr));
Actually, JSON.stringify will ignore non-numeric keys in Array during the Array JSON serialization. From the latest ECMA Spec, in section "24.3.2.4 Runtime Semantics: SerializeJSONArray ( value )", we know JSON.stringify only utilizes length of Array and related numeric keys to do the serialization, and Array length will not be affected by its non-numeric keys. So it is now clear why 'v' (non-numeric keys) disappear in your final result.
You can't use a string as an array index, unless it is a string representation of an integer.
Therefore, arr['v'] has no meaning.
This stackoverflow question goes into more detail, but the relevant part:
Yes, technically array-indexes are strings, but as Flanagan elegantly
put it in his 'Definitive guide':
"It is helpful to clearly distinguish an array index from an object
property name. All indexes are property names, but only property names
that are integers between 0 and 232-1 are indexes."
In JavaScript, basically two types of array, Standard array and associative array. Standard array is defined by [], so 0 based type indexes. And in associative array is defined by {}, in this case you can define string as keys. So in your code you are using both is single array, that's not acceptable. So define the another array if you want strings keys.
I would like to loop through an array and get the key and value of it. This is what I'm doing, but I don't get any output. What am I doing wrong?
let regexes = [];
regexes['some.thing'] = /([^.]+)[.\s]*/g;
_.each(regexes, function(regex, key) {
console.log(regex, key);
});
You are using array and adding a property to it which is not valid .Use object for it
let regexes = {};
regexes['some.thing'] = /([^.]+)[.\s]*/g;
_.each(regexes, function(regex, key) {
console.log(regex, key);
});
_.each iterates through the indices of the array. You are adding a non-numeric property to the array object. Your array is empty and _.each callback is not executed. It seems you want to use a regular object ({}) and not an array:
let regexes = {};
Now _.each should iterate through the object own (by using hasOwnProperty method) properties.
You are assigning a property to the array. Lodash is attempting to iterate through the numeric indices of the array, but there are none. Change the array to an object and Lodash will iterate through its enumerable properties:
let regexes = {};
regexes['some.thing'] = /([^.]+)[.\s]*/g;
_.forEach(regexes, function(regex, key) {
console.log(regex, key);
});
Alternatively, if using an array is necessary, simply push the value onto it:
let regexes = [];
regexes.push(/([^.]+)[.\s]*/g);
_.forEach(regexes, function(regex, i) {
console.log(regex, i);
});
Having the following object obj:
{"Point Ref":[15629989,564646414,65494949],
"Effective Date":["2008-03-03","2010-12-14","2004-10-01"],
"Identifier":["EM","EM","SC"],"Status":["FI","SI","XC"]}"
I can select the first array with
obj["Point Ref"]
How can I select more of them? (like obj["Point Ref", "Identifier"]
This will iterate through all the first-level arrays in the object:
var obj = {"Point Ref":[15629989,564646414,65494949],
"Effective Date":["2008-03-03","2010-12-14","2004-10-01"],
"Identifier":["EM","EM","SC"],"Status":["FI","SI","XC"]};
for (var key in obj) {
if (obj[key] instanceof Array) {
console.log(obj[key]);
}
}
Then depending on what you actually want from this, you can either use a multi-dimensional array or concat them. For multidimensional you would do:
var multi = [];
....
multi.push(obj[key]);
For a single dimensional array you would do:
var single = [];
....
single = single.concat(obj[key]);
You can use concat() to build a new array from several existing ones:
var data = obj["Point Ref"].concat(obj["Identifier"]);
If you're looking for the call to return two values, like say in Matlab, it isnt supported.
Look here for alternate options on returning multiple values: Return multiple values in JavaScript?
I have Hash obj:
var obj = {a,b,c,...};
obj = $H(obj);
I need to convert it to simple array
[a,b,c,..]
How can I do?
Thx.
Object.getValues(myObject) to get an Array of all values.
Object.getKeys(myObject) to get an Array of keys.
For 1.2 simply, Hash provides the same methods.
And don't use Objects {} to store lists like in your example. Arrays are for lists, Objects are for associative arrays.
EDIT:
Since version 1.3 Object.getValues and Object.getKeys has been deprecated and replaced by Object.keys resp Object.values.
since you use $H I am assuming older ver of mootools, 1.2.x since it got deprecated in 1.3 in favour of the new Object. construct
The hash had a .each method:
var Hobj = $H({
tool: "bar",
ghost: "goblin"
});
var arr = [];
Hobj.each(function(value, key) {
arr.push(value); // what to do with key?
});
console.log(arr);
an alternative that grabs the complete objects with their keys but not as array keys:
Hobj.each(function(value, key) {
var obj = {};
obj[key] = value;
arr.push(obj);
});
Assuming you want the values in the array:
var arr = [];
for(var prop in obj){
if(obj.hasOwnProperty(prop)){
arr.push(obj[prop]);
}
}
If you want the property names to be in the array:
var arr = [];
for(var prop in obj){
if(obj.hasOwnProperty(prop)){
arr.push(prop);
}
}
the hasOwnProperty call is important because it will filter out inherited functions and private members of the mooTools hash class that you don't probably want in your resulting array