Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
969 views
in Technique[技术] by (71.8m points)

json - How to extract values from an array of arrays in Javascript?

I have a variable as follows:

var dataset = {
"towns": [
    ["Alada?", "Adana", [35.4,37.5], [0]],
    ["Ceyhan", "Adana", [35.8,37], [0]],
    ["Feke", "Adana", [35.9,37.8], [0]]
    ]
};

The variable has a lot of town data in it. How can I extract the first elements of the third ones from the data efficiently? I,e, what will ... be below?

var myArray = ...
//myArray == [35.4,35.8,35.9] for the given data 

And what to do if I want to store both values in the array? That is

var myArray = ...
//myArray == [[35.4,37.5], [35.8,37], [35.9,37.8]] for the given data 

I'm very new to Javascript. I hope there's a way without using for loops.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

On newer browsers, you can use map, or forEach which would avoid using a for loop.

var myArray = dataset.towns.map(function(town){
  return town[2];
});
// myArray == [[35.4,37.5], [35.8,37], [35.9,37.8]]

But for loops are more compatible.

var myArray = [];
for(var i = 0, len = dataset.towns.length; i < len; i++){
  myArray.push(dataset.towns[i][2];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...