简体   繁体   English

如何将数组值联接为键以获取jSON对象值

[英]How to join Array Values as keys to get jSON object value

I have been working on a function that loops through a JSON object recursively, and want to use each key it finds as the class value of an element to change the .text value of that element in jQuery. 我一直在研究一个递归地遍历JSON对象的函数,并希望使用它找到的每个键作为元素的类值来更改jQuery中该元素的.text值。 So, far so good, however, as I am able to get the Keys recursively as well, I'm struggling on finding a way to input all of those keys to get each json objects values: 因此,尽管如此,我也能够递归地获取Keys,我正努力寻找一种方法来输入所有这些key以获取每个json对象的值:

function eachRecursive(obj, aKey)
{
    aKey = aKey === null ? '' : aKey;

    for (var k in obj)
    {
        if (typeof obj[k] == "object" && obj[k] !== null)
        {
            aKey += k + '_';
            eachRecursive(obj[k], aKey);
        }
        else
        {
            if (obj.hasOwnProperty(k))
            {
                console.log(obj[k]);

                if ($('.player_' + aKey + k).length)
                {
                    var props = aKey.split('_');
                    props.clean("");



                    $('.player_' + aKey + k).text(obj[k]);
                }
            }
            // might not even need this.
            aKey = '';
        }
    }
}

So, text(obj[k]) isn't going to work here since the json is looping through objects inside objects recursively. 因此, text(obj[k])在这里不起作用,因为json递归地遍历对象内部的对象。

So, aKey is a string that gets used to check if the class exists (should be appending each key of the json object into it. Than should check if exists, if it does exist, should plug in the value into the .text of that element. 因此, aKey是用于检查类是否存在的字符串(应在其中添加json对象的每个键。应检查是否存在(如果存在),应将值插入该.text中。元件。

But what I'm sruggling here with is how to get the value from all of the keys that get plugged into an array called, props . 但是,我在这里的问题是如何从插入到称为props的数组的所有键中获取值。 So I will need to use each value in the array as keys for obj object to get the corresponding json value. 因此,我将需要使用数组中的每个值作为obj对象的键,以获取相应的json值。

Can someone please help me here? 有人可以在这里帮我吗?

The .clean prototype added to Array just simply removes any empty values in the array. 添加到Array.clean原型仅删除Array中的任何空值。 Specifically the last array index (since it splits on _ ). 特别是最后一个数组索引(因为它在_拆分)。

How to pass array values into obj to get the json value? 如何将数组值传递到obj以获取json值?

For Example, if: 例如,如果:

var props = ['name', 'first', 'last'];

// How to do this so we can get the value?
obj['name']['first']['last'][k]

Iterate over the props array and lookup the value in turn using bracket notation. 遍历props数组并使用括号表示法依次查找值。

var value = obj;
for (var i = 0; i < props.length; i++) {
    value = value[props[i]];
}
value = value[k];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM