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

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.

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

Array element as Json field [duplicate]

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]))

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

Assigning multiple indices at once from one list [duplicate]

This question already has answers here:
JavaScript Object Literals & Array Literals
(4 answers)
Closed 5 years ago.
I have five user variables with different names. I'd like them to end up in an array, and am wondering if I can do the assignment to multiple array indices in a single line. Currently, if I do this
var users = {user5k, user10k, user15k, user20k, user25k};
I can't index it later (says users[0] is undefined). So I want the indices built in to the assignment. Something along these lines:
var users = {};
users[0:4] = {user5k, user10k, user15k, user20k, user25k};
This doesn't seem possible in JavaScript, meaning I have to do this:
var users = {};
users[0] = user5k;
users[1] = user10;
// ... et cetera
Is there a way to accomplish the first solution?
When you use {} you're creating an object, not an array. Use [] for arrays.
var users = [user5k, user10k, user15k, user20k, user25k];
If you want to replace part of an array that already exists, you can use Array.prototype.splice()
var users = [];
users.splice(0, 4, [user5k, user10k, user15k, user20k, user25k]);

javascript: not getting proper results with callback function [duplicate]

This question already has answers here:
Length of a JavaScript object
(43 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I looked at similar questions and tried Object.key(patientList).length but it returns 0. I was recommended to use callbacks and this how I am implementing it.
var data;
var patientList = {};
var parseDate = d3.time.format("%d/%m/%y").parse;
function input_Data() {
d3.json("data.php", function(error, json) {
if (error) return console.warn(error);
data = json;
console.log(data);
for(var i = 0; i < data.length; i++) {
var name = data[i].name;
//data[i].dates = parseDate(data[i].dates);
if(!patientList[name]) {
var newPatient = {
dates: [data[i].dates],
alpha: data[i].alpha,
beta: data[i].beta
};
patientList[name] = newPatient;
} else {
patientList[name].dates.push(data[i].dates);
}
}
console.log(patientList);
console.log(Object.keys(patientList).length);
console.log(Object.keys(patientList));
});
}
function number_of_patients(callback) {
callback();
console.log(patientList);
console.log(Object.keys(patientList).length);
console.log(Object.keys(patientList));
}
number_of_patients(input_Data);
console.log inside the input_Data function displays correct results with length 4. And console.log in the number_of_patients displays correct patientList but 0 length and doesn't display name (keys) either. I have read similar posts but still can't fix the problem here.
Any help would be much appreciated.
In Javascript, generic objects do not have a length property.
Common facts about Javascript objects:
Objects contain key: value pairs where the keys are strings and values may be any type.
Objects do not have a .keys() method to get all of the keys, except...
Ecmascript 5 provides an Object.keys() which can be called explicitly as do some 3rd party libs like underscore.js
initialized using curly braces {} and key:value pairs
Before that, the usual way to count or access all of the keys unique to a specific instance of an object is with a loop like the following:
l=0;
for(var k in obj){
if (obj.hasOwnProperty(k)){
// hasOwnProperty ignores keys from the prototype chain
// do something with key k, value obj[k]
++l;
}
}
// the object has l keys specific to this instance
If you need to quickly get a length you should consider using an array object:
Array objects (x = [1,2,3,'sam',{'name':'fred', 'status': 'dead'}]) have numeric indices starting with 0 and can contain arbitrary type members.
have a length property (x.length is 5)
values are accessed by numeric indices with square brackets, i.e. x[2] is 3
initialized use square brackets [] containing a comma separated list of values
And as others said in comments, asynchronous calls generally return immediately -- and without the data or object you want in scope. To access the data you must execute code in the context where the data is defined, i.e. write code that accesses the asynchronous data/object in a callback function, not the main code.

Categories