通过搜索另一个变量来获取json变量

时间:2018-07-23 11:56:02

标签: javascript jquery json

我有一些像这样的json数据:

{
"views": [{
    "url": "\/en",
    "viewname": "Home",
    "pagetitle": "My wonderful home page",
    "description": "This is the home page of a wonderful site"
}, {
    "url": "\/en\/about",
    "viewname": "About",
    "pagetitle": "About this wonderful site",
    "description": "All about this wonderful site"
}]
}

我使用像这样的ajax调用加载此数据:

var url = '/sitemap';
views = $.getJSON(url);

我想做的是这样的: viewname ='Home'的页面标题的值是什么?

我正在使用jquery-但纯JavaScript也很不错。

5 个答案:

答案 0 :(得分:0)

您可以在$.getJSON的成功回调中编写逻辑,以便搜索在JSON结果的views数组中的对象数组中进行。由于views是对象数组,因此可以在find()属性上使用viewname操作,以将其值与Home匹配。 ({viewname})是一种仅获取viewname属性值而不是整个属性的破坏方式。

var url = '/sitemap';
$.getJSON(url, function(result){
    var arr = result.views;
    var findObj = arr.find(({viewname}) => 'Home');
    if(findObj){
      //here is your pagetitle
      console.log(findObj.pagetitle);
    }

});

答案 1 :(得分:0)

您可以使用纯JavaScript来简单地做到这一点:

 const myItem = views.find((el) => {
      return el.viewname === 'Home';
});

console.log(myItem.pagetitle)

这将返回第一个具有viewname ==='Home'的元素

答案 2 :(得分:0)

您可以使用以下内容:

var arr = [{
  "url": "\ / en ",
  "viewname": "Home",
  "pagetitle": "My wonderful home page",
  "description": "This is the home page of a wonderful site"
}, {
  "url": "\/en\/about",
  "viewname": "About",
  "pagetitle": "About this wonderful site",
  "description": "All about this wonderful site"
}]



var viewname = 'Home';
var pagetitle = arr.find(o => o.viewname === viewname).pagetitle;
console.log(pagetitle);

答案 3 :(得分:0)

内存不足:

views.views[0].viewname == 'home'

然后

views.views[0].pagetitle== 'My wonderful home page'

答案 4 :(得分:0)

尝试一下:

var obj = {
"views": [{
    "url": "\/en",
    "viewname": "Home",
    "pagetitle": "My wonderful home page",
    "description": "This is the home page of a wonderful site"
}, {
    "url": "\/en\/about",
    "viewname": "About",
    "pagetitle": "About this wonderful site",
    "description": "All about this wonderful site"
}]
};

var viewName = 'Home';
var selectedObj = obj.views.find(item => item.viewname === viewName);
console.log(selectedObj.pagetitle);