[removed] How can I transform an array?

前端 未结 6 934
-上瘾入骨i
-上瘾入骨i 2021-01-12 05:10

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

6条回答
  •  温柔的废话
    2021-01-12 05:27

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

提交回复
热议问题