如何从JSON对象中的数组中获取键名及其值

时间:2020-11-29 23:47:17

My Problem

In my JSON file I have an object within an object with a value which is an array of key/value pairs. I am having trouble outputting each key name and its value.

在我的JSON文件中,我在一个对象中有一个对象,其值是一个键/值对的数组。我输出每个密钥名称及其值时遇到问题。

My Code

menu.json

{"themenu":[
    {
        "stuff": "stuffs",
        "pages": [
            {"name1": "page111"},
            {"name2": "page222"},
            {"name3": "page333"}
        ]
    }
]}

menu.js

$(function() {
    $.getJSON('menu.json', function(data) {
        $(data.themenu).each(function() {
            var stuff = this.stuff;
            alert(stuff); // alerts 'stuffs'
            $(this.pages).each(function(key, value) { 
                var pageName = this.key;
                var pageUrl = this.value;
                alert(pageName + ' ' + pageUrl);
            })
        })
    })
})

What I Require

我需要什么

I want to output the name of the key and its corresponding value so it would be the same as this...

我想输出密钥的名称及其对应的值,因此它将与此相同...

alert('name1 page111');
alert('name2 page222');
alert('name3 page333');

What I've Tried

我试过的

I've tried a few things including...

我尝试过一些事情,包括......

$(data.pages).each(function(key, value) { 
    var pageName = this.key;
    var pageUrl = this.value;
})

...and a bunch more voodoo that I'm too embarrassed to post.

......还有一堆伏都教,我太尴尬了。

3 个解决方案

#1


2  

Just use this code, it will work. I just changed some content of your code, try this::

只需使用此代码即可。我只是改变了你的代码的一些内容,试试这个::

var json_data = {"themenu":[
    {
        "stuff": "stuffs",
        "pages": [
            {"name1": "page111"},
            {"name2": "page222"},
            {"name3": "page333"}
        ]
    }
]};
$(document).ready(function() {
//  $.getJSON(json_data, function(data) {
        $(json_data.themenu).each(function() {
            var stuff = this.stuff;
            alert(stuff); // alerts 'stuffs'
            $(this.pages).each(function(key, value) { 
                $.each(this, function(key, value) {
                    var pageName = key;
                    var pageUrl = value;
                    alert(pageName + ' ' + pageUrl);
                });
            });
        });
//    })
});

Assuming var json_data having your data, Replace it as you need.

假设var json_data包含您的数据,请根据需要替换它。

#2


2  

When looping your JSON and using this.key/this.value you literally search for key key/value (if it would be {'key': ..., 'value': ...}.

在循环你的JSON并使用this.key / this.value时,你会逐字搜索键值/值(如果它是{'key':...,'value':...}。

Your $.each(this.pages, function (key, value) gives you array of your desired value. You can loop once more to get key/value as text:

您的$ .each(this.pages,function(key,value)为您提供所需值的数组。您可以再次循环以获取键/值作为文本:

var json = {
  "pages": [{
    "name1": "page111"
  }, {
    "name2": "page222"
  }, {
    "name3": "page333"
  }]
};

$.each(json.pages, function(k, v) {
  console.log(k, v);
  $.each(this, function(key, value) {
    console.log('->', key, value);
    //alert(keyName + ' ' + value);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

#3


2  

You can iterate over an array with vanilla JavaScript with the forEach method, and then retrieve the keys for an object with Object.keys().

您可以使用forEach方法使用vanilla JavaScript迭代数组,然后使用Object.keys()检索对象的键。

var json_data = {
  "themenu": [{
    "stuff": "stuffs",
    "pages": [{
      "name1": "page111"
    }, {
      "name2": "page222"
    }, {
      "name3": "page333"
    }]
  }]
}


json_data['themenu'].forEach(function(menu) {
  menu.pages.forEach(function(page) {
    alert(Object.keys(page)[0] + ' ' + page[Object.keys(page)[0]]);
  });
});

#1


2  

Just use this code, it will work. I just changed some content of your code, try this::

只需使用此代码即可。我只是改变了你的代码的一些内容,试试这个::

var json_data = {"themenu":[
    {
        "stuff": "stuffs",
        "pages": [
            {"name1": "page111"},
            {"name2": "page222"},
            {"name3": "page333"}
        ]
    }
]};
$(document).ready(function() {
//  $.getJSON(json_data, function(data) {
        $(json_data.themenu).each(function() {
            var stuff = this.stuff;
            alert(stuff); // alerts 'stuffs'
            $(this.pages).each(function(key, value) { 
                $.each(this, function(key, value) {
                    var pageName = key;
                    var pageUrl = value;
                    alert(pageName + ' ' + pageUrl);
                });
            });
        });
//    })
});

Assuming var json_data having your data, Replace it as you need.

假设var json_data包含您的数据,请根据需要替换它。

#2


2  

When looping your JSON and using this.key/this.value you literally search for key key/value (if it would be {'key': ..., 'value': ...}.

在循环你的JSON并使用this.key / this.value时,你会逐字搜索键值/值(如果它是{'key':...,'value':...}。

Your $.each(this.pages, function (key, value) gives you array of your desired value. You can loop once more to get key/value as text:

您的$ .each(this.pages,function(key,value)为您提供所需值的数组。您可以再次循环以获取键/值作为文本:

var json = {
  "pages": [{
    "name1": "page111"
  }, {
    "name2": "page222"
  }, {
    "name3": "page333"
  }]
};

$.each(json.pages, function(k, v) {
  console.log(k, v);
  $.each(this, function(key, value) {
    console.log('->', key, value);
    //alert(keyName + ' ' + value);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

#3


2  

You can iterate over an array with vanilla JavaScript with the forEach method, and then retrieve the keys for an object with Object.keys().

您可以使用forEach方法使用vanilla JavaScript迭代数组,然后使用Object.keys()检索对象的键。

var json_data = {
  "themenu": [{
    "stuff": "stuffs",
    "pages": [{
      "name1": "page111"
    }, {
      "name2": "page222"
    }, {
      "name3": "page333"
    }]
  }]
}


json_data['themenu'].forEach(function(menu) {
  menu.pages.forEach(function(page) {
    alert(Object.keys(page)[0] + ' ' + page[Object.keys(page)[0]]);
  });
});