Lee
Lee

Reputation: 1495

Javascript - JSON String to Array

This is driving me mad, I have a JSON string that looks like so:

[["OX", "139.38"], ["LE", "131.28"], ["SA", "105.45"]]

I want to convert this to an array so that I can I can take advantage of indexOf:

alert(myArray.indexOf("LE"));

I've tried to convert my JSON string to an array using JSON.parse(myJSON) and jQuery.parseJSON(myJSON) but neither work.

How can I create an array from my JSON string? I'm happy to set up a loop just not sure how.

Upvotes: 0

Views: 76

Answers (3)

Pedro Justo
Pedro Justo

Reputation: 4289

If you want to get index at outter array:

var x = '[["OX", "139.38"], ["LE", "131.28"], ["SA", "105.45"]]';
var y = JSON.parse(x);

function getIndexByKey(key,array){
  for(var i=0, len = array.length; i<len;i++){
    if(array[i][0] === key){
      return i;
    }
  }
}

function getIndexByVal(val,array){
  for(var i=0, len = array.length; i<len;i++){
    if(array[i][1] === val){
      return i;
    }
  }    
}

calling it:

getIndexByKey('OX', y); //0
getIndexByKey('LE', y); // 1
getIndexByKey('SA', y)  // 2

getIndexByVal('139.38', y); //0
...

Upvotes: 0

KungWaz
KungWaz

Reputation: 1956

This will convert it like this [[""OX", "139.38"], ["LE", "131.28""]] -> ["OX", "LE"]

var newArr = [];

for(var i = 0; i < myArr.length; i++) {
    newArr.push(myArr[i][0]);
}

This will convert it like this [[""OX", "139.38"], ["LE", "131.28""]] -> ["OX", "139.38", "LE", "131.28"]

var newArr = [];

for(var i = 0; i < myArr.length; i++) {
    var tempArr = myArr[i];
    for(var j = 0; j < tempArr.length; j++) {
        newArr.push(tempArr[j]);
    }
}

Now you can use indexOf.

Upvotes: 0

Chris Charles
Chris Charles

Reputation: 4446

This works in chrome console:

var s = '[["OX", "139.38"], ["LE", "131.28"], ["SA", "105.45"]]';
var a = JSON.parse(s);

// a = [["OX", "139.38"],["LE", "131.28"],["SA", "105.45"]]

If you want to create a data structure to lookup the values by the keys:

var dict = {};
for (var i=0; i<a.length; i++){
    dict[a[i][0]] = a[i][1];
}

Now dict looks like this:

//dict = {OX:"139.38", LE:"131.28", SA:"105.45"}

and we can index into it with the keys

dict['LE'] // = "131.28"

Upvotes: 1

Related Questions