Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How can I transform an array?

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

like image 551
MEM Avatar asked Aug 31 '10 15:08

MEM


People also ask

What is [] vs {} in JS?

[] 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.

Can you change the elements in an array?

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

How do you transform an array into an object?

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.

Can we change the value of array in JavaScript?

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.


1 Answers

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:

  • The order of enumeration is not guaranteed, properties may not be visited in the numeric order.
  • Enumerates also inherited properties.

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"]
like image 77
Christian C. Salvadó Avatar answered Oct 05 '22 06:10

Christian C. Salvadó