I have this on a javascript var: (it's a http returned data, and I don't know if it's an array or string - (how can we see that?) - Update: using typeof returned "string", so it's a string.
[{"nomeDominio":"gggg.fa"},{"nomeDominio":"rarar.fa"}]
How can we pass/transform that, into something like this:
["gggg.fa","rarar.fa"]
?
Thanks a lot, MEM
[] is declaring an array. {} is declaring an object. An array has all the features of an object with additional features (you can think of an array like a sub-class of an object) where additional methods and capabilities are added in the Array sub-class.
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
To convert an array into an object we will create a function and give it 2 properties, an array and a key. const convertArrayToObject = (array, key) => {}; We will then reduce the array, and create a unique property for each item based on the key we have passed in.
Javascript is pass by value, and which essentially means part is a copy of the value in the array. To change the value, access the array itself in your loop.
You can figure out if is a string or an already parsed object by checking the type of your variable, e.g.:
ajax('url', function (response) {
alert(typeof response);
});
You will now figure out if it's a "string"
or an Array "object"
.
If it's a string, you can use the JSON.parse
method as @alcuadrado suggest, otherwise you can simply use the array.
Several answers suggest the use of the for-in
statement to iterate over the array elements, I would discourage you to use it for that.
The for-in
statement should be used to enumerate over object properties, to iterate over Arrays or Array-like objects, use a sequential loop as @Ken Redler suggests.
You should really avoid for-in
for this purpose because:
You can also use the Array.prototype.map
method to meet your requirements:
var response = [{"nomeDominio":"gggg.fa"},{"nomeDominio":"rarar.fa"}];
var array = response.map(function (item) { return item.nomeDominio; });
// ["gggg.fa", "rarar.fa"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With