Get from JSON object with string IDs to JS numeric IDs [duplicate] - javascript

This question already has answers here:
Is there any way to use a numeric type as an object key?
(11 answers)
Closed 4 years ago.
i have a JSON object (sent from php) and I want to convert the IDs to a numeric key using JS. So currently it looks something like that:
let foo = {"66":"test","65":"footest"};
And now I want it to look like this:
let foo = {66:"test",65:"footest"};

Object keys do not need to be numerical to be accessed - as noted in the comments - they are strings regardless.- Below, I am console logging the "66" property using the brackets notation - foo[66]
let foo = {"66":"test","65":"footest"};
console.log(foo[66]); // gives "test"
// if you want to assign values numerically - ie using the index of a loop - then you could do
for(i = 63; i<65; i++) {
foo[i] = "test" + i;
}
console.log(foo); // gives {"63": "test63", "64": "test64","65": "footest","66": "test"}

Related

Struggling with Javascript Object Array adding keys [duplicate]

This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 5 years ago.
I have this snippet of code:
var arrLiteData = [];
for(ii=0;ii<10;ii++)
{
arrLiteData.push({ii:{"field1":100,"field2":ii}});
}
...but instead of ii taking the increasing numeric value of ii, the array just holds the actual variable name, like this:
[{"ii":{"field1":100,"field2":0}},{"ii":{"field1":100,"field2":1}}...etc, etc...
What am I doing wrong?
Many thanks.
Quotes are optional for javascript object keys, so
{ii:{"field1":100,"field2":ii}} is the same as
{"ii":{"field1":100,"field2":ii}} or even
{ii:{field1:100,field2:ii}}. They are just need if you have non alphanumeric characters.
To solve this you could either use a computed key if you're transpiling your code or targeting recent navigators:
{[ii]:{"field1":100,"field2":ii}}
Or build the object in two steps:
var arrLiteData = [];
for(ii=0;ii<10;ii++)
{
var obj = {};
obj[ii] = {"field1":100,"field2":ii};
arrLiteData.push(obj);
}

How to parse json in javascript having dynamic key value pair? [duplicate]

This question already has answers here:
How do I enumerate the properties of a JavaScript object? [duplicate]
(14 answers)
Closed 7 years ago.
I want to parse a JSON string in JavaScript. The response is something like
var response = '{"1":10,"2":10}';
How can I get the each key and value from this json ?
I am doing this -
var obj = $.parseJSON(responseData);
console.log(obj.count);
But i am getting undefined for obj.count.
To access each key-value pair of your object, you can use Object.keys to obtain the array of the keys which you can use them to access the value by [ ] operator. Please see the sample code below:
Object.keys(obj).forEach(function(key){
var value = obj[key];
console.log(key + ':' + value);
});
Output:
1 : 10
2 : 20
Objects.keys returns you the array of the keys in your object. In your case, it is ['1','2']. You can therefore use .length to obtain the number of keys.
Object.keys(obj).length;
So you need to access it like an array, because your keys are numbers. See this fiddle:
https://jsfiddle.net/7f5k9het
You can access like this:
result[1] // this returns 10
result.1 // this returns an error
Good luck

How to change the given below json array? [duplicate]

This question already has answers here:
Extract each value of a single property from an array of objects in jQuery
(5 answers)
Closed 9 years ago.
I have a JSON array in the following format:
[{"country":"Algeria"},{"country":"Africa"},{"country":"America"},{"country":"Libiya"}]
I need to change it as follows:
{"Algeria","Africa","America","Libiya"}
How do I do that using Jquery or JavaScript?
In javascript:
var myArray = [{"country":"Algeria"},{"country":"Africa"},{"country":"America"},{"country":"Libiya"}];
var myNewArray = [];
for (var item in myArray) {
var country = myArray[item].country;
myNewArray.push(country);
}
alert(JSON.stringify(myNewArray));
You're actually have the wrong notation in your question. The end result you want should have square brackets ([]), not curly braces({}). Curly braces indicate an object instead of an array but you are not using a key-value structure so the end-result you have above is actually invalid.
Instead it seems you want ["Algeria","Africa",America","Libiya"] as the end-result.
Assuming you mean literally changing the array you have rather than creating a new one and assuming you are using JavaScript:
var arr = [{"country":"Algeria"},{"country":"Africa"},{"country":"America"},{"country":"Libiya"}], // declare your array upfront (but this could be a `JSON.parse()` call)
i = 0, // counter
l = arr.length; // limit/length of array
for (i; i < l; i += 1) {
arr[i] = arr[i].country; // Replace object with value of country property.
}
// `arr` will now be `["Algeria","Africa",America","Libiya"]`
Of course you might want to introduce some checks to ensure that every element of the array has a property called country and some way to deal with that in the rewritten array. But I'll leave you with this for now, see how you get on. This should work if your array is valid to begin with.

javascript data attribute read by name when name is dynamically generated [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I add a property to a Javascript Object using a variable as the name?
Dynamic property names for loop of object Javascript
In success of javascript function I receveing data and it look like this:
data.lvl1
data.lvl2
data.lvl3
...
let say I have only 3 elements in data and I would like to loop for each of them and rise alert for every level:
for(a = 1; a<= 3; a++)
{
alert(data.lvl + a);
//I would like to read lvl1, lvl2, lvl3
}
This approach is obviously wrong.
Please explain how to reach lvl1, lvl2 in loop when lvl number is based on increasing a.
If you want to access a property name using a string, then use square bracket notation.
foo.bar === foo['bar']
Such:
alert(data['lvl' + a]);
But it would be better to restructure your data so that you had something like:
data = { lvl: [1,2,3] }
instead of
data = { lvl1: 1, lvl2: 2, lvl3: 3 }

Updating a result in JSON with a dynamic variable name [duplicate]

This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
Closed 8 years ago.
I need to update a value in my JSON.
My JSON result looks like this:
results = {"ROWCOUNT":50,"COLUMNS":["PERSONID","NAME"],"DATA":{"PERSONID":["42","43","44"], "NAME":["JOE","TOM","JANE"]}
resultData = results.DATA
In the below code I am looping over the result set and attempting to update a value at a position. I believe it is failing because I am not using dynamic variables correctly.
var columnName = "NAME";
for(i=0; i < results.ROWCOUNT; i++ ){
resultData.columnName[i] = "foo" // failing here due to "columnName" being dynamic.
}
Figured it out.. You have to use array syntax
resultData[columName][i]

Categories