如何对数组中相同key统一赋值?

有以下两个数组, 其中'name'后缀的数字由arr决定。arr数组有多长,array里的name就有多少个

              let arr=[0,1,2,3];

let array=[

{

name0:'1',

name1:'',

name2:'',

name3:'',

},

{

name0:'',

name1:'',

name2:'2',

name3:'',

},

{

name0:'',

name1:'6',

name2:'',

name3:'',

},

{

name0:'',

name1:'',

name2:'',

name3:'9',

},

]

如何使得数组中相同key的value一样,效果如下

       array=[

{

name0:'1',

name1:'6',

name2:'2',

name3:'9',

},

{

name0:'1',

name1:'6',

name2:'2',

name3:'9',

},

{

name0:'1',

name1:'6',

name2:'2',

name3:'9',

},

{

name0:'1',

name1:'6',

name2:'2',

name3:'9',

},

]


回答:

let arr = [0, 1, 2, 3];

let array = [

{

name0: '1',

name1: '',

name2: '',

name3: '',

},

{

name0: '',

name1: '',

name2: '2',

name3: '',

},

{

name0: '',

name1: '6',

name2: '',

name3: '',

},

{

name0: '',

name1: '',

name2: '',

name3: '9',

},

];

let values = {};

// 遍历数组,更新values对象

array.forEach(item => {

arr.forEach((_, index) => {

let key = 'name' + index;

if (item[key]) {

values[key] = item[key];

}

});

});

array = array.map(() => {

let newObj = {};

arr.forEach((_, index) => {

let key = 'name' + index;

newObj[key] = values[key] || '';

});

return newObj;

});

console.log(array);

如何对数组中相同key统一赋值?


回答:

我假设你希望将所有非空键的值分配给其他相同键的项。如果这是你的需求,你可以用循环来实现。以下是一个例子:

let array=[

{name0:'1', name1:'', name2:'', name3:''},

{name0:'', name1:'', name2:'2', name3:''},

{name0:'', name1:'6', name2:'', name3:''},

{name0:'', name1:'', name2:'', name3:'9'}

];

for(let i = 0; i < array.length; i++) {

for(let key in array[i]) {

if(array[i][key] !== '') {

for(let j = 0; j < array.length; j++) {

if(array[j][key] === '') {

array[j][key] = array[i][key];

}

}

}

}

}

console.log(array);


回答:

用HashMap

以上是 如何对数组中相同key统一赋值? 的全部内容, 来源链接: utcz.com/p/934943.html

回到顶部