如何将Javascript OBJECT / JSON中的所有项分隔到数组中

时间:2017-04-03 14:07:42

标签: javascript jquery json

好的,这是Javascript对象/ JSON:

{
    "marco":{
        "gender":"men",
        "age":29,
        "children":{
            "jen":{
                "gender":"women",
                "age":14
            },
            "marco jr.":{
                "gender":"men",
                "age":16,
                "children":{
                    "Koos":{
                        "gender":"men",
                        "age":1
                    }
                }
            }
        }
    },
    "lisa":{
        "gender":"women",
        "age":20
    },
    "mike":{
        "gender":"men",
        "age":32,
        "children":{
            "carl":{
                "gender":"women",
                "age":19
            }
        }
    }
}

如果我选择 marco ,我想要输出

["jen":{"gender":"women", "age":14}, "marco jr.":{"gender":"men", "age":16}, "Koos":{"gender":"men", "age":1}]

用语言来说:需要将具有多个图层的大对象切成1个大数组。所以没有三个物体了。

我无法想到任何解决方案。

3 个答案:

答案 0 :(得分:1)

这是一个适合递归函数的任务,因为你需要找到Marco的所有孩子,他们所有的孩子,等等。像这样:(JSFiddle

function getDescendents(family, memberName) {
    function inner(children, r) {
        for (var k in children) {
            if (children.hasOwnProperty(k)) {
                r[k] = {
                    age: children[k].age,
                    gender: children[k].gender
                };
                inner(children[k].children, r);
            }
        }
    }

    var r = {};
    inner(family[memberName].children, r);
    return r;
}
console.log(getDescendents(family, 'marco'));

这实际上是对嵌套对象进行展平 - 所以也可以看到以前的答案,例如Fastest way to flatten / un-flatten nested JSON objects; One liner to flatten nested object; Flattening deeply nested array of objects

这假设您要返回一个名称为键的对象,而不是一个数组(只能有索引号)。

答案 1 :(得分:0)

您可以使用递归来执行此操作。当您匹配父名称时,您需要将true添加到递归的下一次迭代,以便它知道添加到结果。



var obj = {"marco":{"gender":"men","age":29,"children":{"jen":{"gender":"women","age":14},"marco jr.":{"gender":"men","age":16,"children":{"Koos":{"gender":"men","age":1}}}}},"lisa":{"gender":"women","age":20},"mike":{"gender":"men","age":32,"children":{"carl":{"gender":"women","age":19}}}}

function toArray(data, name, parent) {
  var result = [];
  for (var i in data) {
    if(i == name || parent == true) {
    	if(i != name) result.push({[i]: {gender: data[i].gender, age: data[i].age}})
    	result = result.concat(toArray(data[i].children, name, true))
    }

    result = result.concat(toArray(data[i].children, name, false))
  }
  return result;
}

console.log(JSON.stringify(toArray(obj, 'marco', false), 0, 4))
console.log(JSON.stringify(toArray(obj, 'marco jr.', false), 0, 4))
console.log(JSON.stringify(toArray(obj, 'mike', false), 0, 4))




答案 2 :(得分:-3)

如果您使用javascript搜索json对象,请使用“ JSON.parse()”函数。

请查看此页面https://www.w3schools.com/js/js_json_parse.asp

或者,如果您使用的是PHP,请使用“ json_decode()”方法将其转换为数组