gpt4 book ai didi

javascript - JS - 合并对象

转载 作者:行者123 更新时间:2023-12-02 01:26:18 24 4
gpt4 key购买 nike

我需要合并/组合内部的 4 个对象和数组。这些对象是:

{"field": "name","lang": "it","text": "RegoleAziendali"}
{"field": "pdf_url","lang": "it", "text": "docs/it/file.pdf"}
{"field": "name","lang": "en","text": "CompanyRules"}
{"field": "pdf_url","lang": "en", "text": "docs/en/file.pdf"}

预期结果应该由语言合并的 2 个对象组成。

{"lang": "it","name": "RegoleAziendali","pdf_url":"docs/it/file.pdf"}
{"lang": "en","name": "CompanyRules","pdf_url":"docs/en/file.pdf"}

目前我正在使用 array.forEach 按 lang 合并两个对象。但我找不到操纵值/属性的方法。正如您所看到的,合并对象中不再需要属性“field”。

最佳答案

假设您有一个数组,您可以将其转换为分组问题。

使用reducelang分组。
之后使用 Object.values

获取分组对象的值数组

const x = [
{"field": "name","lang": "it","text": "RegoleAziendali"},
{"field": "pdf_url","lang": "it", "text": "docs/it/file.pdf"},
{"field": "name","lang": "en","text": "CompanyRules"},
{"field": "pdf_url","lang": "en", "text": "docs/en/file.pdf"}
]

const res = Object.values(x.reduce((acc,{field,lang,text}) => {
acc[lang] = acc[lang] || {lang}
acc[lang][field] = text
return acc
},{}))

console.log(res)

使用 for 循环可以完成同样的事情

const x = [{"field": "name","lang": "it","text": "RegoleAziendali"},{"field": "pdf_url","lang": "it", "text": "docs/it/file.pdf"},{"field": "name","lang": "en","text": "CompanyRules"},{"field": "pdf_url","lang": "en", "text": "docs/en/file.pdf"}]

const res = {}
for (const entry of x){
const {field,lang,text} = entry
res[lang] = res[lang] || {lang}
res[lang][field] = text
}

console.log(Object.values(res))

关于javascript - JS - 合并对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74538311/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com