减少嵌套对象数组

huangapple go评论74阅读模式
英文:

Reduce array of nested objects

问题

以下是您要翻译的内容:

我有一个如下所示的嵌套对象的动态数组:

[
    {
        "fields": [
            {
                "field-1": {
                    "id": "field-1",
                    "value": "a1"
                },
                "field-2": {
                    "id": "field-2",
                    "value": "a2"
                },
                "field-3": {
                    "id": "field-3",
                    "value": "a3"
                }
            }
        ]
    },
    {
        "fields": [
            {
                "field-1": {
                    "id": "field-1",
                    "value": "b1"
                },
                "field-2": {
                    "id": "field-2",
                    "value": "b2"
                },
                "field-3": {
                    "id": "field-3",
                    "value": "b3"
                }
            }
        ]
    }
]

我想要将这个数组解析/减少为以下类型的结构:

[
    {
        "field-1": "a1",
        "field-2": "a2",
        "field-3": "a3"
    },
    {
        "field-1": "b1",
        "field-2": "b2",
        "field-3": "b3"
    },
]
虽然我已经有一种详细的方法来遍历数组并构建新数组,但我想知道是否可以使用reduce方法来获得该结构,因为那将更快?

请告诉我您需要的进一步帮助。

英文:

I have a dynamic array of nested objects as below:

[
    {
        "fields": [
            {
                "field-1": {
                    "id": "field-1",
                    "value": "a1"
                },
                "field-2": {
                    "id": "field-2",
                    "value": "a2"
                },
                "field-3": {
                    "id": "field-3",
                    "value": "a3"
                }
            }
        ]
    },
    {
        "fields": [
            {
                "field-1": {
                    "id": "field-1",
                    "value": "b1"
                },
                "field-2": {
                    "id": "field-2",
                    "value": "b2"
                },
                "field-3": {
                    "id": "field-3",
                    "value": "b3"
                }
            }
        ]
    }
]

I want to parse/reduce this array to below kind of structure:

[
    {
		"field-1": "a1",
		"field-2": "a2",
		"field-3": "a3"
	},
    {
		"field-1": "b1",
		"field-2": "b2",
		"field-3": "b3"
	},
]

While I already have a verbose way of iterating over the array and constructing the new one, I wanted to know if it is possible to get the structure using the reduce method, as that would be faster?

答案1

得分: 5

你可以使用reduce来实现它:

const result = raw
  .map(row => Object.entries(row.fields[0])
    .reduce((acc, [key, { value }]) => {
       acc[key] = value
       return acc
    }, {})
  )

console.log(result)
英文:

You can use reduce to do it

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const result = raw
  .map(row =&gt; Object.entries(row.fields[0])
    .reduce((acc, [key, { value }]) =&gt; {
       acc[key] = value
       return acc
    }, {})
  )

console.log(result)

<!-- language: lang-html -->

&lt;script&gt;
  const raw = [{
      &quot;fields&quot;: [{
        &quot;field-1&quot;: {
          &quot;id&quot;: &quot;field-1&quot;,
          &quot;value&quot;: &quot;a1&quot;
        },
        &quot;field-2&quot;: {
          &quot;id&quot;: &quot;field-2&quot;,
          &quot;value&quot;: &quot;a2&quot;
        },
        &quot;field-3&quot;: {
          &quot;id&quot;: &quot;field-3&quot;,
          &quot;value&quot;: &quot;a3&quot;
        }
      }]
    },
    {
      &quot;fields&quot;: [{
        &quot;field-1&quot;: {
          &quot;id&quot;: &quot;field-1&quot;,
          &quot;value&quot;: &quot;b1&quot;
        },
        &quot;field-2&quot;: {
          &quot;id&quot;: &quot;field-2&quot;,
          &quot;value&quot;: &quot;b2&quot;
        },
        &quot;field-3&quot;: {
          &quot;id&quot;: &quot;field-3&quot;,
          &quot;value&quot;: &quot;b3&quot;
        }
      }]
    }
  ]
&lt;/script&gt;

<!-- end snippet -->

答案2

得分: 3

以下是您要翻译的代码部分:

var convert = [];
for (let i = 0; i < test.length; i++) {
    var obj = {};
    Object.entries(test[i]).forEach(entry => {
        const [key, value] = entry;
        for (let j = 0; j < value.length; j++) {
            Object.entries(value[j]).forEach(s => { var [k, v] = s; obj[k] = v.value });
        }
    })
    convert[i] = obj
}
console.log(convert);
<script>
var test = [
    {
        "fields": [
            {
                "field-1": {
                    "id": "field-1",
                    "value": "a1"
                },
                "field-2": {
                    "id": "field-2",
                    "value": "a2"
                },
                "field-3": {
                    "id": "field-3",
                    "value": "a3"
                }
            }
        ]
    },
    {
        "fields": [
            {
                "field-1": {
                    "id": "field-1",
                    "value": "b1"
                },
                "field-2": {
                    "id": "field-2",
                    "value": "b2"
                },
                "field-3": {
                    "id": "field-3",
                    "value": "b3"
                }
            }
        ]
    }
];
</script>
英文:

You Can try this code

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var convert=[];
for (let i=0; i&lt; test.length; i++){
    var obj={};
    Object.entries(test[i]).forEach(entry =&gt; { 
        const [key, value] = entry; 
        for(let j=0; j &lt; value.length; j++){
            Object.entries(value[j]).forEach(s =&gt; { var [ k,v ] = s; obj[k]= v.value  }); 
        }
    })
    convert[i]=obj
}
console.log(convert);

<!-- language: lang-html -->

&lt;script&gt;
var test=[
    {
        &quot;fields&quot;: [
            {
                &quot;field-1&quot;: {
                    &quot;id&quot;: &quot;field-1&quot;,
                    &quot;value&quot;: &quot;a1&quot;
                },
                &quot;field-2&quot;: {
                    &quot;id&quot;: &quot;field-2&quot;,
                    &quot;value&quot;: &quot;a2&quot;
                },
                &quot;field-3&quot;: {
                    &quot;id&quot;: &quot;field-3&quot;,
                    &quot;value&quot;: &quot;a3&quot;
                }
            }
        ]
    },
    {
        &quot;fields&quot;: [
            {
                &quot;field-1&quot;: {
                    &quot;id&quot;: &quot;field-1&quot;,
                    &quot;value&quot;: &quot;b1&quot;
                },
                &quot;field-2&quot;: {
                    &quot;id&quot;: &quot;field-2&quot;,
                    &quot;value&quot;: &quot;b2&quot;
                },
                &quot;field-3&quot;: {
                    &quot;id&quot;: &quot;field-3&quot;,
                    &quot;value&quot;: &quot;b3&quot;
                }
            }
        ]
    }
];&lt;/script&gt;

<!-- end snippet -->

答案3

得分: 2

以下是翻译好的部分:

JSON.parse reviverJSON.stringify replacer 可以用于修改嵌套值:

const data = [{"fields":[{"field-1":{"id":"field-1","value":"a1"},
                          "field-2":{"id":"field-2","value":"a2"},
                          "field-3":{"id":"field-3","value":"a3"}}]},
              {"fields":[{"field-1":{"id":"field-1","value":"b1"},
                          "field-2":{"id":"field-2","value":"b2"},
                          "field-3":{"id":"field-3","value":"b3"}}]}]

let result = JSON.parse(JSON.stringify(data), (k, v) => v.value ?? v.fields?.[0] ?? v)

console.log( result )

希望这对你有所帮助。

英文:

The JSON.parse reviver and JSON.stringify replacer can be used to modify nested values :

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const data = [{&quot;fields&quot;:[{&quot;field-1&quot;:{&quot;id&quot;:&quot;field-1&quot;,&quot;value&quot;:&quot;a1&quot;},
                          &quot;field-2&quot;:{&quot;id&quot;:&quot;field-2&quot;,&quot;value&quot;:&quot;a2&quot;},
                          &quot;field-3&quot;:{&quot;id&quot;:&quot;field-3&quot;,&quot;value&quot;:&quot;a3&quot;}}]},
              {&quot;fields&quot;:[{&quot;field-1&quot;:{&quot;id&quot;:&quot;field-1&quot;,&quot;value&quot;:&quot;b1&quot;},
                          &quot;field-2&quot;:{&quot;id&quot;:&quot;field-2&quot;,&quot;value&quot;:&quot;b2&quot;},
                          &quot;field-3&quot;:{&quot;id&quot;:&quot;field-3&quot;,&quot;value&quot;:&quot;b3&quot;}}]}]

let result = JSON.parse(JSON.stringify(data), (k, v) =&gt; v.value ?? v.fields?.[0] ?? v)

console.log( result )

<!-- end snippet -->

答案4

得分: 0

以下是您的版本:

// 开始代码段
const res = data
  .flatMap((obj) => obj.fields)
  .map((obj) =>
    Object.entries(obj).reduce((p, [k, v]) => ({ ...p, [k]: v.value }), {})
  );

console.log(JSON.stringify(res, null, 4));
// 结束代码段
<script>
  const data = [
    {
      "fields": [
        {
          "field-1": {
            "id": "field-1",
            "value": "a1"
          },
          "field-2": {
            "id": "field-2",
            "value": "a2"
          },
          "field-3": {
            "id": "field-3",
            "value": "a3"
          }
        }
      ]
    },
    {
      "fields": [
        {
          "field-1": {
            "id": "field-1",
            "value": "b1"
          },
          "field-2": {
            "id": "field-2",
            "value": "b2"
          },
          "field-3": {
            "id": "field-3",
            "value": "b3"
          }
        }
      ]
    }
  ]
</script>

解释:

首先,我们使用 flatMap() 处理给定的数组,因为我们有嵌套的数组,以获得如下结果:

const x = data.flatMap((obj) => obj.fields);

输出:

[
  {
    "field-1": {
      "id": "field-1",
      "value": "a1"
    },
    "field-2": {
      "id": "field-2",
      "value": "a2"
    },
    "field-3": {
      "id": "field-3",
      "value": "a3"
    }
  },
  {
    "field-1": {
      "id": "field-1",
      "value": "b1"
    },
    "field-2": {
      "id": "field-2",
      "value": "b2"
    },
    "field-3": {
      "id": "field-3",
      "value": "b3"
    }
  }
]

现在,对于上述数组中的每个对象,我们只需要更改每个对象中每个键的值。因此,我们需要在先前的输出上调用 map,并为每个对象生成我们想要的对象,使用 reduce()

const res = x.map((obj) => Object.entries(obj).reduce((p, [k, v]) => ({ ...p, [k]: v.value }), {}));

输出:

[
  {
    "field-1": "a1",
    "field-2": "a2",
    "field-3": "a3"
  },
  {
    "field-1": "b1",
    "field-2": "b2",
    "field-3": "b3"
  }
]
英文:

Here is my version:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const res = data
  .flatMap((obj) =&gt; obj.fields)
  .map((obj) =&gt;
    Object.entries(obj).reduce((p, [k, v]) =&gt; ({ ...p,
      [k]: v.value
    }), {})
  );

console.log(JSON.stringify(res, null, 4));

<!-- language: lang-html -->

&lt;script&gt;
  const data = [{
      &quot;fields&quot;: [{
        &quot;field-1&quot;: {
          &quot;id&quot;: &quot;field-1&quot;,
          &quot;value&quot;: &quot;a1&quot;
        },
        &quot;field-2&quot;: {
          &quot;id&quot;: &quot;field-2&quot;,
          &quot;value&quot;: &quot;a2&quot;
        },
        &quot;field-3&quot;: {
          &quot;id&quot;: &quot;field-3&quot;,
          &quot;value&quot;: &quot;a3&quot;
        }
      }]
    },
    {
      &quot;fields&quot;: [{
        &quot;field-1&quot;: {
          &quot;id&quot;: &quot;field-1&quot;,
          &quot;value&quot;: &quot;b1&quot;
        },
        &quot;field-2&quot;: {
          &quot;id&quot;: &quot;field-2&quot;,
          &quot;value&quot;: &quot;b2&quot;
        },
        &quot;field-3&quot;: {
          &quot;id&quot;: &quot;field-3&quot;,
          &quot;value&quot;: &quot;b3&quot;
        }
      }]
    }
  ]
&lt;/script&gt;

<!-- end snippet -->

Explanation

We first flatMap() the given array since we have array inside array, to get the following:

const x = data.flatMap((obj) =&gt; obj.fields);

Output:

[
    {
        &quot;field-1&quot;: {
            &quot;id&quot;: &quot;field-1&quot;,
            &quot;value&quot;: &quot;a1&quot;
        },
        &quot;field-2&quot;: {
            &quot;id&quot;: &quot;field-2&quot;,
            &quot;value&quot;: &quot;a2&quot;
        },
        &quot;field-3&quot;: {
            &quot;id&quot;: &quot;field-3&quot;,
            &quot;value&quot;: &quot;a3&quot;
        }
    },
    {
        &quot;field-1&quot;: {
            &quot;id&quot;: &quot;field-1&quot;,
            &quot;value&quot;: &quot;b1&quot;
        },
        &quot;field-2&quot;: {
            &quot;id&quot;: &quot;field-2&quot;,
            &quot;value&quot;: &quot;b2&quot;
        },
        &quot;field-3&quot;: {
            &quot;id&quot;: &quot;field-3&quot;,
            &quot;value&quot;: &quot;b3&quot;
        }
    }
]

Now for each object in the above array, I just need to change the value of each key in each object. So we need to call map on the previous output and for each object, generate our desired object using reduce():

const res = x.map((obj) =&gt; Object.entries(obj).reduce((p, [k, v]) =&gt; ({ ...p, [k]: v.value }), {}))

Output:

[
    {
        &quot;field-1&quot;: &quot;a1&quot;,
        &quot;field-2&quot;: &quot;a2&quot;,
        &quot;field-3&quot;: &quot;a3&quot;
    },
    {
        &quot;field-1&quot;: &quot;b1&quot;,
        &quot;field-2&quot;: &quot;b2&quot;,
        &quot;field-3&quot;: &quot;b3&quot;
    }
]

huangapple
  • 本文由 发表于 2023年5月13日 16:11:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76241726.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定