[英]Javascript creates new arrays based on conditions
我有旧数组和实体数组:
var old = [
{
"id": 3,
"entity_type_id": 1,
"product_id": 4,
"name": "test1",
"acreage": 100,
"yield": 20,
"worth": 30
},
{
"id": 4,
"entity_type_id": 1,
"product_id": 4,
"name": "test2",
"acreage": 10,
"yield": 20,
"worth": 0
},
{
"id": 5,
"entity_type_id": 3,
"product_id": 5,
"name": "test3",
"acreage": 20,
"yield": 20,
"worth": 40
}
]
var entity = [
{"id": 1, "name": "a1"},
{"id": 2, "name": "a2"},
{"id": 3, "name": "a3"}
]
我希望得到以下数据:
var newArr = [ { "id": 3, "entity_type_id": 1, "product_id": 4, "name": "test1", "acreage": 110, "yield": 40, "worth": 30, "entity_type_1": 2, // The total amount of entity_type_id (entity_type_id: 1) "entity_type_2": 0, "entity_type_3": 0 }, { "id": 5, "entity_type_id": 3, "product_id": 5, "name": "test3", "acreage": 20, "yield": 20, "worth": 40, "entity_type_1": 0, "entity_type_2": 0, "entity_type_3": 1 // The total amount of entity_type_id (entity_type_id: 3) } ] console.log(newArr)
我尝试了以下代码并获得了一些数据。 我不确定是否会有任何异常或错误。
更何况,我不知道如何处理实体数组数据。 有人可以帮我解决这个问题并得到我期望的结果吗?
非常感谢 !
function mergeArr(arr) {
const temp = []
arr.forEach((dataItem) => {
if (temp.length) {
let filterValue = temp.filter((items) => {
return items.product_id === dataItem.product_id
})
if (filterValue.length) {
temp.forEach((n) => {
if (n.product_id === filterValue[0].product_id) {
n.yield = dataItem.yield + filterValue[0].yield
n.acreage = dataItem.acreage + filterValue[0].acreage
n.worth = dataItem.worth + filterValue[0].worth
}
})
} else {
temp.push(dataItem)
}
} else {
temp.push(dataItem)
}
})
return temp
}
Youi 可以找到 object 并总结想要的属性。 对于entity
,采用另一个循环和 map 新条目并从中构建新的 object 以进行传播。
var old = [{ id: 3, entity_type_id: 1, product_id: 4, name: "test1", acreage: 100, yield: 20, worth: 30 }, { id: 4, entity_type_id: 1, product_id: 4, name: "test2", acreage: 10, yield: 20, worth: 0 }, { id: 5, entity_type_id: 3, product_id: 5, name: "test3", acreage: 20, yield: 20, worth: 40 }], entity = [{ id: 1, name: "a1" }, { id: 2, name: "a2" }, { id: 3, name: "a3" }], entityTypes = Object.fromEntries(entity.map(({ id }) => ['entity_type_' + id, 0])), result = old.reduce((r, o) => { let temp = r.find(q => q.product_id === o.product_id); if (.temp) r.push(temp = {.., o. ..;entityTypes }), else ['acreage', 'yield'. 'worth'];forEach(k => temp[k] += o[k]). temp['entity_type_' + o;entity_type_id]++; return r, }; []). console;log(result);
.as-console-wrapper { max-height: 100%;important: top; 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.