8

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

4
  • shudnt the keys in key-value pairs be unique? Commented Aug 31, 2010 at 15:11
  • good question. I don't know. I'm having always the same keys because this is what I do get from json_encode php function, after a fetch_obj. Commented Aug 31, 2010 at 15:14
  • @Kasturi this isn't a KVP in the 'traditional' sense, it's an array of two objects, each of which have a nomeDominio property. Commented Aug 31, 2010 at 15:17
  • @Katsuri - they are unique within the object. There just happen to be many objects here. Commented Aug 31, 2010 at 15:17

6 Answers 6

9

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"]
Sign up to request clarification or add additional context in comments.

6 Comments

Great answer bro, I didn't know the difference of sequential loop and for-in in arrays. The first snippet may look a little confusing though, whats that ajax function? And how can a response give you a parsed array? Thanks (:
+1 for map(). Sadly, you have to make your own (conditional) implementation if you want IE7/8 along for the ride. IE9 has it, though.
Thanks a lot CMS for your great comment and detail. I have used alcuadrado suggestion because it was a string, after using typeof as suggested.
@alcuadrado: You're welcome, the ajax function is just a library-agnostic example of an Ajax request, which the OP presumably does.
@Ken: Yeah, IE9 is getting pretty good!, the Sept. 15 they will release another Platform Preview Release :)
|
8

This question is strongly related with this one.

I would suggest reading my answer there, as it would really help; and with a little variation, it would just work:

var responseString = '[{"nomeDominio":"gggg.fa"},{"nomeDominio":"rarar.fa"}]',
    responseObject = JSON.parse(responseString),
    nombresDeDominio = [];

for(var i in responseObject) {
  nombresDeDominio.push(responseObject[i].nomeDominio)
}

Suerte!

Comments

1

Assuming your data always looks like that, you can do something like this:

var foo = [{"nomeDominio":"gggg.fa"},{"nomeDominio":"rarar.fa"}];
var newarr = [];
for ( var i=0,j=foo.length;i<j;i++ ) {
    newarr.push( foo[i]['nomeDominio'] );
}

Here's a working fiddle.

1 Comment

Thanks a lot. I really must see much more for in order to use them when I need one. We may not know if a language as a given sintax keyword but, for is almost certain. Thanks a lot for exemplifying with one.
1
function transform(array, f) {
    var ret = [];
    $.each(array, function(index) {
        var v = f.call(this, index);
        if(v) {
            ret.push(v);
        }
    });
    return ret;
}

var result = transform(
    [{"nomeDominio":"gggg.fa"},{"nomeDominio":"rarar.fa"}], 
    function() { return this.nomeDominio; }
);

alert(result.toString());

Comments

0

it's a http returned data, and I don't know if it's an array or string

It's JSON, and you can use it directly in JavaScript.

If you transform it into your array, you will lose the association key / value ; are you sure it's what you want ?

1 Comment

Not sure really. I'm loosing all my faith here. The point is to pass this data to a autocomplete plugin and, I don't understand what that plugin wants. I'm completely lost here. It's related: stackoverflow.com/questions/3609581/… X.X
0

Okay, firstly to get the type of a "thing", use the "typeof" operator (note that the type of an array is an object, not 'array'!):

var a = "string";
var b = 1;
var c = new Array();
alert(typeof(a)); // string
alert(typeof(b)); // number
alert(typeof(c)); // object

To get at the values in the associative array (assuming it is one), you can just loop through it, like so:

var d = [{"nomeDominio":"gggg.fa"},{"nomeDominio":"rarar.fa"}];
d["bob"] = "alice";
d["gary"] = "stephen";

for(var key in d) {
    alert(d[key]);
}

1 Comment

Thanks. I've used typeof and I will try not to forget that important note about object been an array. ;) Thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.