[英]How to add a field to each object in array and push that result array to another array using react and javascript?
i want to add a field type to each object in an array and push the result to another array and push that to another array.我想为数组中的每个 object 添加一个字段类型,并将结果推送到另一个数组并将其推送到另一个数组。
below is how the array of object looks,下面是 object 数组的样子,
const arrObj1 = [
{
id: '1',
name: 'n1',
},
{
id: '2',
name: 'n2',
}
]
const arrObj2 = [
{
id: '3',
name: 'n3',
},
{
id: '4',
name: 'n4',
}
]
what i am trying to do?我想做什么?
i want to add a type field with value 'type1' to arrObj1 and type field with value 'type2' to arrObj2我想将值为“type1”的类型字段添加到 arrObj1,并将值为“type2”的类型字段添加到 arrObj2
so the output should be like below,所以 output 应该如下所示,
const arrObj1 = [
{
id: '1',
name: 'n1',
type: 'type1',
},
{
id: '2',
name: 'n2',
type: 'type1',
}
]
const arrObj2 = [
{
id: '3',
name: 'n3',
type: 'type2',
},
{
id: '4',
name: 'n4',
type: 'type2',
}
]
then i want to combine these two arrays arrObj1 and arrObj2 into one array like below然后我想将这两个 arrays arrObj1 和 arrObj2 组合成一个数组,如下所示
const combinedArrObj = [
{
id: '1',
name: 'n1',
type: 'type1',
},
{
id: '2',
name: 'n2',
type: 'type1',
},
{
id: '3',
name: 'n3',
type: 'type2',
},
{
id: '4',
name: 'n4',
type: 'type2',
}
]
what i have tried?我试过什么?
const arrObj1Res = arrObj1.map((obj: any) => {
return {
...arrObj1,
type: 'type1',
}
});
const arrObj2Res = arrObj2.map((obj: any) => {
return {
...arrObj2,
type: 'type2',
}
});
const combinedArrObj = [
...arrObj1Res,
...arrObj2Res,
];
this works.这行得通。 but how can i refactor to something simple rather than adding field type for each obj in array and then combine但是我怎样才能重构一些简单的东西而不是为数组中的每个 obj 添加字段类型然后组合
could someone help me with this.有人可以帮我解决这个问题。 thanks.谢谢。
you can use this你可以用这个
let result=arrObj1.concat(arrObj2)
function contains(a, obj) {
for (var i = 0; i < a.length; i++) {
if (a[i] === obj) {
return true;
}
}
return false;
}
result.filter(element => {
if (contains(arrObj1,element) ){
element.type='type1'
return element
}else {
element.type='type2'
return element
}
});
In pure JS, just a simple for loop can do the part where you add a field named type.在纯 JS 中,只需一个简单的 for 循环就可以完成添加名为 type 的字段的部分。
for(var i = 0; i < arrObj1.length; i++){
arrObj1[i].type = "type1";
}
for(var i = 0; i < arrObj2.length; i++){
arrObj2[i].type = "type2";
}
and to combine the arrays together just use concat.并将 arrays 组合在一起,只需使用 concat。
const combinedArrObj = arrObj1.concat(arrObj2);
const allArrayObject = arrObj1.concat(arrObj2);
const finalResultArray = allArrayObject.reduce((finalResultArray, eachArrayObj, index) =>{
const isTypeOne = arrObj1.length - 1 >= index
const relevantTypeString = isTypeOne ? "type1" : "type2"
eachArrayObj.type = relevantTypeString
finalResultArray.push(eachArrayObj)
return finalResultArray
}, [])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.