简体   繁体   English

javascript-从json对象提取数组

[英]javascript - extract array from json object

Let say We have the following json object: 假设我们有以下json对象:

[{"a1" : "a1Val", "a2" : "a2Val", "a3" : "a3Val"}, 
 {"b1" : "b1Val", "b2" : "b2Val", "b3" : "b3Val"},

 ....

 {"z1" : "z1Val", "z2" : "z2Val", "z3" : "z3Val"}]

How can we retrieve from this object array of only X2 key value pairs. 我们如何从仅X2键值对的对象数组中检索。

meaning, the following result: 意思是,以下结果:

 [ {"a2" : "a2Val"}, {"b2" : "b2Val"}, ... ,{ "z2" : "z2Val"}] 

within the best performance. 在最佳性能范围内。

The key does not have to contains number. 密钥不必包含数字。

What I need here is a function that will recieve parameter - i and return an array of all the i-th objects in the original json object 我在这里需要的是一个将接收参数的函数-i并返回原始json对象中所有第i个对象的数组

So for example if we look at the above json object and we invoke the method we 2 the method will return 例如,如果我们看上面的json对象,然后调用方法2,该方法将返回

 [ {"a2" : "a2Val"}, {"b2" : "b2Val"}, ... ,{ "z2" : "z2Val"}] 

Hope it's clear enough. 希望它足够清楚。

You could use Array.map here 你可以在这里使用Array.map

var arr = oldArr.map(function(obj){
    var key = Object.keys(obj).sort()[1], rtn = {};    
    return rtn[key] = obj[key], rtn;
});

What you're doing is taking the second key and then returning a new Object with that key and value. 您正在做的是获取第二个键,然后返回具有该键和值的新Object。

var initialArr = [
                  {"a1" : "a1Val", "a2" : "a2Val", "a3" : "a3Val"}, 
                  {"b1" : "b1Val", "b2" : "b2Val", "b3" : "b3Val"},
                  {"z1" : "z1Val", "z2" : "z2Val", "z3" : "z3Val"}
                 ];

var resArr = initialArr.map(function(x){
    return x[Object.keys(x)[1]];
});

jsFiddle Demo jsFiddle演示

Here in this resArr, I am mapping it to initialArr[ ], to generate an array out of it called resArr and the each element initialArr is represented as 'x' in this x is an object now inorde to get the 2nd element of the object x[1] so here, 1 represents the second element as index starts from 0,1 ,,,so we need to get the keys of that object by Object.keys(x)[1]...hence value would be x[Object.keys(x)[1]]. 在这里,在此resArr中,我将其映射到initialArr [],以从中生成一个名为resArr的数组,每个元素initialArr在此x中均表示为“ x”,这是一个对象,现在可以获取该对象的第二个元素x [1]因此,这里的1代表第二个元素,因为索引从0,1,...开始,因此我们需要通过Object.keys(x)[1] ...获得该对象的键,因此值将是x [Object.keys(x)[1]]。

Just a really fancy way to do exactly what you asked. 这是一种完全按照您的要求做的花哨的方法。 Applicable to anything after little tweaking 微调后适用于任何东西

var json   = '[{"a1" : "a1Val", "a2" : "a2Val", "a3" : "a3Val"},{"b1" : "b1Val", "b2" : "b2Val", "b3" : "b3Val"},{"z1" : "z1Val", "z2" : "z2Val", "z3" : "z3Val"}]',
    parsed = JSON.parse(json),
    index  = 2, // here goes your value

    result = parsed.map(function(obj){
               var key = Object.keys(obj)[0][0]+index,
                   retDict = {};
               return retDict[key] = obj[key], retDict;
             });

Run this in a console and see. 在控制台中运行它,看看。

You will probably find that it is more efficient to do this when parsing your JSON string by using a reviver function. 您可能会发现,使用reviver函数解析JSON字符串时,这样做更有效。 Something like this. 这样的事情。

 var json = '[{"a1" : "a1Val", "a2" : "a2Val", "a3" : "a3Val"},{"b1" : "b1Val", "b2" : "b2Val", "b3" : "b3Val"},{"z1" : "z1Val", "z2" : "z2Val", "z3" : "z3Val"}]', data = JSON.parse(json, function (key, value) { if (key !== "" && typeof value === 'object') { Object.keys(value).forEach(function (name) { if (name.slice(-1) !== '2') { delete value[name]; } }); } return value; }); document.body.appendChild(document.createTextNode(JSON.stringify(data))); 

Do a forEach loop on the array. 在数组上执行forEach循环。 Then for each value get the key with a regular expression. 然后为每个值获取带有正则表达式的键。 ( Loop through object get value using regex key matches Javascript ). 使用正则表达式键匹配Javascript遍历对象获取值 )。 I won't give you the full code because it is easy to implement and it is a good learning experience. 我不会给您完整的代码,因为它易于实现,并且是一种很好的学习体验。

Convert to array, map the keys, filter results, concat it all, etc. This should work for you: 转换为数组,映射键,筛选结果,合并所有内容,等等。这应该对您有用:

var result = arr
    .map(function (obj) { 
        return Object.keys(obj).map(function (key) {
            var result = {};
            result[key] = obj[key];

            if (key.substring(1) === "2") {
                return result;
            }
        });
    })
    .reduce(function (x, y) { return x.concat(y); }, [])
    .filter(function (obj) { return obj });

See working fiddle . 参见工作提琴

What about this: 那这个呢:

var collection, key, obj, objArr, _i, _len, _tmp;

collection = [
  {
    "a1": "a1Val",
    "a2": "a2Val",
    "a3": "a3Val"
  }, {
    "b1": "b1Val",
    "b2": "b2Val",
    "b3": "b3Val"
  }
];

objArr = [];

for (_i = 0, _len = collection.length; _i < _len; _i++) {
  obj = collection[_i];
  for (key in obj) {
    _tmp = {};
    _tmp[key] = obj[key];
    objArr.push(_tmp);
  }
}

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

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