当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - jQuery: print all the values from multiple keys within a nested array

问题描述:

I have a nested array in json as followed:

var json.result= [

{"id":"0","category":"Camera","name":"600D Kit", "condition":"OK"},

{"id":"1","category":"Camera","name":"600D Kit", "condition":"missing cap"},

{"id":"2","category":"Camera","name":"7D Kit", "condition":"OK"}]

And this is what I am trying to do:


1/ Find every "name" in the array.


2/ Print the values of "id" and "category" that belongs to the "name" accordingly

Ideal result:


equipment id = 0


category: Camera


name: 600D Kit

equipment id = 1


category: Camera


name: 600D Kit

equipment id = 2


category: Camera


name: 7D Kit

This is my attempt:

var equipmentName = [];

var listLength = json.result.length;

while (listLength--){

equipmentName[listLength] = json.result[listLength].name

}

console.log(equipmentName);

var equipment = json.result.find(function(e){

return e.name == equipmentName;

});

console.log("equipment id: " + equipment.id);

console.log("category: " +equipment.category);

console.log("name: " +equipment.name);

I am able to print all the values of "names" within the array, and print the "id", "category" and "name" of the first item of the array if return e.name;. However, once I added return e.name == equipmentName; , I got an error of "equipment

网友答案:

This code will display all your elements to the console.

var result= [
{"id":"0","category":"Camera","name":"600D Kit", "condition":"OK"},    
{"id":"1","category":"Camera","name":"600D Kit", "condition":"missing cap"},        
{"id":"2","category":"Camera","name":"7D Kit", "condition":"OK"}];

result.map(function(element){  
  console.log(element.id,element.category,element.name);  
  // Element display functions here
});
分享给朋友:
您可能感兴趣的文章:
随机阅读: