代码之家  ›  专栏  ›  技术社区  ›  GwynBleidD

如何从父元素获取包含字段的所有子元素的列表

  •  11
  • GwynBleidD  · 技术社区  · 6 年前

    源数据:

    [
        {
            "name": "A",
            "foo": "x",
            "bar": 1,
            "subelements": [
                {
                    "baz": "xyz",
                    "foobar": "abc"
                },
                {
                    "baz": "zzz",
                    "foobar": "def"
                }
            ]
        },
        {
            "name": "B",
            "foo": "Y",
            "bar": 4,
            "subelements": [
                {
                    "baz": "yyy",
                    "foobar": "aaa"
                },
                {
                    "baz": "xxx",
                    "foobar": "bbb"
                },
                {
                    "baz": "www",
                    "foobar": "bbb"
                }
            ]
        }
    ]
    

    预期结果:

    [
        {
            "baz": "xyz",
            "foobar": "abc",
            "foo": "x"
        },
        {
            "baz": "zzz",
            "foobar": "def",
            "foo": "x"
        },
        {
            "baz": "yyy",
            "foobar": "aaa",
            "foo": "Y"
        },
        {
            "baz": "xxx",
            "foobar": "bbb",
            "foo": "Y"
        },
        {
            "baz": "www",
            "foobar": "bbb",
            "foo": "Y"
        }
    ]
    
    2 回复  |  直到 6 年前
        1
  •  4
  •   Lahiru Jayakody    6 年前

    如果没有父节点引用,这目前是不可能做到的。父节点访问仍然是 listed as a feature request

        2
  •  -1
  •   Nicholas Pipitone    6 年前

    ans = [];
    input.forEach(elem =>
        elem["subelements"].forEach(subElem => {
            ans.push(Object.assign({
                foo: a["foo"]
            }, subElem))
        })
    );
    

    或者,如果你更喜欢FP,

    ans = Array.prototype.concat.apply([], input.map(elem =>
        elem["subelements"].map(subElem =>
            Object.assign({
                foo: a["foo"]
            }, subElem)
        )
    ));
    

    Object.assign({foo: a["foo"]}, elem) 具有 {foo: a["foo"], ...elem} [].concat(...input.map(_))