the reference answer GPT ᴼ ᴾ ᴱ ᴺ ᴬ ᴵ < br / > can be done according to the following steps:
Traverses the arr1 array, generates the corresponding Type attribute value, and merges the value of Type to generate a new attribute name.
Walk through the arr2 array, adding the newly generated property name to the array object.
Combine the chr_ attribute name in arr1 with the value of Type to generate a new attribute name, add it to the arr2 array object, and assign it as an empty string.
Here is the code implementation:
let arr1 = [
{
Num: "0001",
chr_Beijing: "xx",
chr_Shanghai: "xx"
},
{
Num: "0002",
chr_Beijing: "xx",
chr_Shanghai: "xx"
},
{
Num: "0003",
chr_Beijing: "xx",
chr_Shanghai: "xx"
}
]
let arr2 = [
{
Num: "0001",
Type: "T1",
T1_Beijing: "",
chr_Beijing: "xx",
T1_Shanghai: "",
chr_Shanghai: "xx"
},
{
Num: "0002",
Type: "T2",
T2_Beijing: "",
chr_Beijing: "xx",
T2_Shanghai: "",
chr_Shanghai: "xx"
},
{
Num: "0003",
Type: "T3",
T3_Beijing: "",
chr_Beijing: "xx",
T3_Shanghai: "",
chr_Shanghai: "xx"
}
]
for (let i = 0; i < arr1.length; i++) {
let num = arr1[i].Num.replace(/^0+/, ''); // 去掉前导0的整数
let type = "T" + num;
let keys = Object.keys(arr1[i]);
for (let j = 0; j < keys.length; j++) {
let key = keys[j];
if (key.indexOf("chr_") === 0) {
let city = key.replace("chr_", "");
let newKey = type + "_" + city;
arr2[i][newKey] = "";
}
}
}
Code description:
-
removes the leading 0 from the Num attribute using the regular expression.
-
Gets an array of property names for objects in arr1 by using the Object.keys() method.
-
Traverses the array of attribute names to determine whether it begins with chr_, and if so generates a new attribute name and adds it to the corresponding array object in arr2.