Array element as Json field [duplicate] - javascript

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 4 years ago.
Basically I have a json say..
collectionData = {'customerName':'Ashish','phone':'1234567'}
Now I have an array containing json fieldnames like..
array = ['customerName','phone'];
Now I want to perform this operation :
for (let i = 0; i < array.length; i++) {
console.log(collectionData.array[i]);
}
Why this code is giving me error? Thanks is advance

You'll have to access them using bracket notation. Coz when you do that using . dot notation what happens is
console.log(collectionData.array[0]) // undefined -
//it looks for .array[0] property which gives you undefined
That's why it is advised to use bracket notation in such cases
Now consider the following
console.log(collectionData[array[0]])
This will first resolve array[0] to customerName and will give you value if exists.
If you still want to access using dot notation there is still a way to do that. Something like
var collectionData = {'customerName':'Ashish','phone':'1234567'}
var array = ['customerName','phone'];
for(var i=0; i<array.length; i++)
console.log(eval('collectionData.'+array[i]))

Related

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

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"}

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);
}

Accessing object in javascript [duplicate]

This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
Closed 8 years ago.
Please explain, why this code it's not allowed in javascript and how to make it.
var p = "inputText";
regError.p
This will give me undefined but
regError.inputText
will give me a correct result.
You can do it by using bracket notation:
regError[p]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors
If you have an object like this
var regError = {
inputText : 'something'
}
and you want to access it with a variable, you'll have to use bracket notation
var p = "inputText";
var result = regError[p]; // returns "something"
Use with bracket notation:
regError[p]
You can check the difference between them here and there

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.

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