根据通过选择的另一个数组提供的索引,从以下数组生成另一个数组。 以下数组
array =[`0: Array(2)
0:
disable: false
label: "label0"
1:
disable: false
label: "label1"
1: Array(2)
0:
disable: false
label: "label0"
1:
disable: true
label: "label1"
2: Array(2)
0:
disable: true
label: "label0"
1:
disable: false
label: "label1"
3: Array(2)
0:
disable: false
label: "label0"
1:
disable: true
label: "label1"]
现在,当数组selected = [2,3]
时。禁用真实数据阵列应被赋予优先级。然后结果数组应该是
`0:
disable: true
label: "label0"
1:
disable: true
label: "label1" `
类似地,当数组selected = [0,1]
时
然后,结果应为
0:
disable: false
label: "label0"
1:
disable: true
Edit:label: "label1"
编辑:对不起,我忘了提及这一点。到目前为止,我已经尝试过
checked=[2,3]
arrayData=[
[
{
"label": "label1",
"disable": true
},
{
"label": "label2",
"disable": false
},
],
[
{
"label": "label1",
"disable": false
},
{
"label": "label2",
"disable": false
},
],
[
{
"label": "label1",
"disable": true
},
{
"label": "label2",
"disable": false
},
]
]
const result=this.checked
.map(indexAtArrayData => {
const element = this.arrayData[indexAtArrayData];
const resData=[]
if (element) {
for (var i=0;i<element.length;i++) {
resData[i]={label:element[i].label};
if (element[i].disable || typeof resData[i]['disable'] == 'undefined') {
resData[i].disable=element[i].disable;
}
}
return resData;
}
});console.log(result);
我已经尝试了上面的代码并获得了结果,但是我正在寻找一种更整洁的方式。
答案 0 :(得分:2)
您可以获取第一个包含对象的所需数组的副本,并在必要时更新disable
。
var array = [[{ disable: false, label: "label0" }, { disable: false, label: "label1" }], [{ disable: false, label: "label0" }, { disable: true, label: "label1" }], [{ disable: true, label: "label0" }, { disable: false, label: "label1" }], [{ disable: false, label: "label0" }, { disable: true, label: "label1" }]],
selected = [2, 3],
result = selected.reduce((r, i) => {
if (!r) {
return array[i].map(o => Object.assign({}, o)); // take copy
}
array[i].forEach((o, j) => r[j].disable = r[j].disable || o.disable); // update disable
return r;
}, undefined);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:0)
如果我正确理解这一点,则所选数组代表原始数组的索引,并且要在原始数组的每个所选元素上选择设置为禁用的第一个元素,然后选择其他第一个元素。
这是解决方案的样子:
selectedArray
.map(indexAtArrayData => {
const element = arrayData[indexAtArrayData];
if (element) {
for (let entry of element) {
if (entry.disable) {
return entry;
}
}
return element[0];
}
});
答案 2 :(得分:0)
function processData(arr, selected) {
let processedArray = [];
selected.map(index => {
const element = arr[index];
if (element) {
for (let entry of element) {
let processedEntry = {
label: entry.label
};
if (entry.disable || entry.disable === undefined) {
processedEntry.disable = true;
}
processedArray.push(processedEntry);
}
}
});
return processedArray;
}
这是jsfiddle
的链接