如何在不删除顶层的情况下将嵌套对象移动到顶层?

时间:2015-12-04 16:06:57

标签: javascript underscore.js lodash

假设我有这些数据:

data = [{
    "_id" : "2fApaxgiPx38kpDLA",
    "profile" : {
        "name" : "Karina 1",
        "avatar" : "avatar1.jpg"
        "bio" : "my bio 1"
}
{
    "_id" : "NXM6H4EWfeRAAhB7c",
    "profile" : {
        "name" : "Karina 2",
        "avatar" : "avatar2.jpg"
        "bio" : "my bio 2"
    },
}]

我做了_.map(data, "profile")但删除了顶级_id:

wrongResult = [{
    "name" : "Karina 1",
    "avatar" : "avatar1.jpg"
    "bio" : "my bio 1"
}
{
    "name" : "Karina 2",
    "avatar" : "avatar2.jpg"
    "bio" : "my bio 2"  
}]

如何将嵌套对象移动到顶层而不删除顶层,如下所示:

expectedResult = [{
    "_id" : "2fApaxgiPx38kpDLA",
    "name" : "Karina 1",
    "avatar" : "avatar1.jpg"
    "bio" : "my bio 1"
}
{
    "_id" : "NXM6H4EWfeRAAhB7c",
    "name" : "Karina 2",
    "avatar" : "avatar2.jpg"
    "bio" : "my bio 2"  
}]

非常感谢你......

3 个答案:

答案 0 :(得分:3)

这样的东西? (未经测试)

_.map(data,function(d){
    d.profile._id = d._id;
    return d.profile;
});

答案 1 :(得分:2)

最近需要自己做这样的事情。结束编写通用函数以将所有(嵌套的包含)对象值带到顶层:

const reduceObjValues = (obj, cache = {}) => {
    const objectValues = Object.keys(obj).reduce((acc, cur) => {
        if (!Array.isArray(obj[cur]) && typeof obj[cur] === 'object') {
            return reduceObjValues({ ...acc, ...obj[cur] }, cache);
        }
        acc[cur] = obj[cur];

        return acc;
    }, {});

    return {
        ...objectValues,
        ...cache,
    };
}
reduceObjValues({
  a: {
    b: 'a',
    c: 'b',
  },
  d: {
    e: 'a',
    f: {
      g: {
        h: [
          1,
          2,
          3,
        ]
      }
    }
  }
});
=> { b: 'a', c: 'b', e: 'a', h: [ 1, 2, 3 ] }

此功能的一个问题是它将覆盖任何相同的键。

答案 2 :(得分:0)

您可以使用 flatten 将嵌套对象移动到其父级... https://www.npmjs.com/package/flat