我有一个这样的响应数组:
let firstArray = {
"TEST0":[
"App",
"Desktop",
"Mobile"
],
TEST1": [
"BEVERAGES",
"CLOTHING, PERSONAL ACCESSORIES AND RELATED PRODUCTS"
]
}
我有这样的对象数组:
let secondArray = [
{
created: "2019-05-28T11:13:55.000"
createdBy: ""
displayname: "BEVERAGES"
docname: "BEVERAGES"
id: 1
name: "BEVERAGES"
purposeCode: "P"
responsible: (2) [{…}, {…}]
shortname: "BEVERAGES"
status: "Active"
},
{
created: "2019-05-28T11:13:55.000"
createdBy: ""
displayname: "CLOTHING, PERSONAL ACCESSORIES AND RELATED PRODUCTS"
docname: "CLOTHING, PERSONAL ACCESSORIES AND RELATED PRODUCTS"
id: 2
name: "CLOTHING, PERSONAL ACCESSORIES AND RELATED PRODUCTS"
purposeCode: "P"
responsible: []
shortname: "CLOTHING, PERSONAL ACCESSORIES AND RELATED PRODUCTS"
status: "Active"
}
]
我想检查第二个数组中的显示名称在第一个数组中的位置,并按这样的键将它们分组
例如:
如果我有饮料,APP,那么我将具有以下结构:
{
"TEST0":[
"App",
"Desktop",
"Mobile"
],
TEST1": [
"BEVERAGES":[
{
created: "2019-05-28T11:13:55.000"
createdBy: ""
displayname: "BEVERAGES"
docname: "BEVERAGES"
id: 1
name: "BEVERAGES"
purposeCode: "P"
responsible: (2) [{…}, {…}]
shortname: "BEVERAGES"
status: "Active"
}
]
]
}
我的问题有所不同,因为我有两个数组而不是一个,我想在其中创建一个数组并通过第一个数组中的键将第二个数组分组
答案 0 :(得分:1)
const newData = {}
Object.keys(firstArray).forEach(key => {
newData[key] = firstArray[key].map(e => secondArray.find(i => i.displayname === e) || e);
})
console.log(newData);
答案 1 :(得分:0)
这是您解决问题的方法:
var test = {
TEST0:[
"App",
"Desktop",
"Mobile"
],
TEST1: [
"BEVERAGES",
"CLOTHING, PERSONAL ACCESSORIES AND RELATED PRODUCTS"
]
}
var arr = [
{
created: "2019-05-28T11:13:55.000",
createdBy: "ZIRA",
displayname: "BEVERAGES",
docname: "BEVERAGES",
id: 1,
name: "BEVERAGES",
purposeCode: "P",
responsible: "(2) [{…}, {…}]",
shortname: "BEVERAGES",
status: "Active"
},
{
created: "2019-05-28T11:13:55.000",
createdBy: "ZIRA",
displayname: "CLOTHING, PERSONAL ACCESSORIES AND RELATED PRODUCTS",
docname: "CLOTHING, PERSONAL ACCESSORIES AND RELATED PRODUCTS",
id: 2,
name: "CLOTHING, PERSONAL ACCESSORIES AND RELATED PRODUCTS",
purposeCode: "P",
responsible: "[]",
shortname: "CLOTHING, PERSONAL ACCESSORIES AND RELATED PRODUCTS",
status: "Active",
}
]
var newArr = []
var count = 0
for (let [key, value] of Object.entries(test)) {
if(value.length){
console.log(value);
jsObj1 = {};
value.forEach(function(singleKey , index){
arr.forEach(function(singleObject){
if(singleObject.name == singleKey){
var jsObj1 = {};
var jsObj = {};//newArr[count] = {
jsObj[singleKey] = singleObject;
//newArr.push(jsObj);
jsObj1[key] = jsObj;
newArr.push(jsObj1);
}
});
});
}
}
console.log(newArr);
在newArr
中,您将获得所需的数组。
答案 2 :(得分:0)
尝试一下
const result = {};
for (let testName of Object.keys(response1)) {
if (response1.hasOwnProperty(testName)) {
for (let i = 0; i < response1[testName].length; i++) {
const key = response1[testName][i];
result[key] = response2.filter(el => key === el.displayname)
}
}
}
console.log(result)