json stringify结果获取特定键的值

时间:2014-11-05 03:12:02

标签: javascript json string

[{"displayorder":"1","menuname":"DashBoard","menuid":"5","menuurl":"dashboard.php"},{"displayorder":"3","menuname":"Accounting Module","menuid":"3","menuurl":""},{"displayorder":"4","menuname":"My Profile","menuid":"4","menuurl":"myprofile.php"},{"displayorder":"6","menuname":"HR Module","menuid":"2","menuurl":""},{"displayorder":"9","menuname":"Administrator","menuid":"1","menuurl":""}]

我在这里有一个stringfy json我想知道如何获得这个json对象中所有menuname的值,任何想法赞赏

UPDATE: 我试过这个 here但我在控制台中未定义

UPDATE

[{"displayorder":"1","menuname":"Menu Management","menuid":"1","submenuurl":"","parentid":"1"},{"displayorder":"1","menuname":"hr sub menu","menuid":"7","submenuurl":"error.php","parentid":"2"},{"displayorder":"2","menuname":"Role Management","menuid":"2","submenuurl":"","parentid":"1"},{"displayorder":"2","menuname":"menu 2 management2","menuid":"8","submenuurl":"","parentid":"2"},{"displayorder":"3","menuname":"hrsubmenu","menuid":"3","submenuurl":"contactus.php","parentid":"2"},{"displayorder":"3","menuname":"submenuaccounting","menuid":"4","submenuurl":"imagegallery.php","parentid":"3"}];

如何使用parentid获取第二个json中的所有详细信息,具体取决于上述menuid

2 个答案:

答案 0 :(得分:1)

工作示例:

http://jsfiddle.net/0866pay3/

var json = [{"displayorder":"1","menuname":"DashBoard","menuid":"5","menuurl":"dashboard.php"},{"displayorder":"3","menuname":"Accounting Module","menuid":"3","menuurl":""},{"displayorder":"4","menuname":"My Profile","menuid":"4","menuurl":"myprofile.php"},{"displayorder":"6","menuname":"HR Module","menuid":"2","menuurl":""},{"displayorder":"9","menuname":"Administrator","menuid":"1","menuurl":""}];


json.forEach(function(el, idx){
    console.log(el.menuname);
});

文档更新

如果您查看this article,则会看到以下内容:

  

使用三个参数调用回调:

     
      
  • 元素值
  •   
  • 元素索引
  •   
  • 正在遍历的数组
  •   

因此,idx只是表示元素索引的常用方法。无论你喜欢什么 - theIndexmyRandomName等,你都可以打电话给你。

答案 1 :(得分:1)

var myjson = [{"displayorder":"1","menuname":"DashBoard","menuid":"5","menuurl":"dashboard.php"},{"displayorder":"3","menuname":"Accounting Module","menuid":"3","menuurl":""},{"displayorder":"4","menuname":"My Profile","menuid":"4","menuurl":"myprofile.php"},{"displayorder":"6","menuname":"HR Module","menuid":"2","menuurl":""},{"displayorder":"9","menuname":"Administrator","menuid":"1","menuurl":""}]; 


var menu_names = []; 

for (var x = 0 ; x < myjson.length; x++){
    if(myjson[x].hasOwnProperty('menuname')){
        // do something usefull here 
        console.log(myjson[x]['menuname']);
        // add value to new array 
        menu_names.push(myjson[x]['menuname'])
    }
}

console.log(menu_names);