我有两个数组
def VERSION_CODE = 3
defaultConfig {
applicationId "de.blackunity.germanminelife.germanminelife"
minSdkVersion 15
targetSdkVersion 28
versionName '2.2'
versionCode VERSION_CODE
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
];
const data= [
{ id: 1, value='123'},
{ id: 2, value='456'},
{ id: 3, value='457'},
{ id: 4, value='586'},
];
我想要一个新的数组,它将颜色字段合并到数据数组中。
预期产量
const colors = [
{ color: 'rgba(52, 182, 193, 0.7)' },
{ color: 'rgba(56, 206, 33, 0.7)' },
{ color: 'rgba(208, 88, 216, 0.7)' },
{ color: 'rgba(206, 66, 47, 0.7)' },
{ color: 'rgba(72, 84, 191, 0.7)' },
{ color: 'rgba(222, 249, 47, 0.7)' },
];
newArray应该是数据数组的长度; 有效的方法是什么?
答案 0 :(得分:0)
您可以将.map()
与Object.assign()
一起使用:
const data= [
{ id: 1, value:'123'}, { id: 2, value:'456'},
{ id: 3, value:'457'}, { id: 4, value:'586'}
];
const colors = [
{ color: 'rgba(52, 182, 193, 0.7)' }, { color: 'rgba(56, 206, 33, 0.7)' },
{ color: 'rgba(208, 88, 216, 0.7)' }, { color: 'rgba(206, 66, 47, 0.7)' },
{ color: 'rgba(72, 84, 191, 0.7)' }, { color: 'rgba(222, 249, 47, 0.7)' }
];
const result = data.map((o, i) => Object.assign({}, o, colors[i]));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:0)
您可以简化数组并映射值。这种方法适用于任意数量的数组。
var data= [{ id: 1, value:'123' }, { id: 2, value:'456' }, { id: 3, value:'457' }, { id: 4, value:'586' }],
colors = [{ color: 'rgba(52, 182, 193, 0.7)' }, { color: 'rgba(56, 206, 33, 0.7)' }, { color: 'rgba(208, 88, 216, 0.7)' }, { color: 'rgba(206, 66, 47, 0.7)' }, { color: 'rgba(72, 84, 191, 0.7)' }, { color: 'rgba(222, 249, 47, 0.7)' }],
result = [data, colors]
.reduce((a, b) => a.map((o, i) => Object.assign({}, o, b[i])));
console.log(result);
答案 2 :(得分:0)
如果您想要高效,快速的解决方案,请不要使用map,而应使用for循环:
const data= [
{ id: 1, value:'123'}, { id: 2, value:'456'},
{ id: 3, value:'457'}, { id: 4, value:'586'}
];
const colors = [
{ color: 'rgba(52, 182, 193, 0.7)' }, { color: 'rgba(56, 206, 33, 0.7)' },
{ color: 'rgba(208, 88, 216, 0.7)' }, { color: 'rgba(206, 66, 47, 0.7)' },
{ color: 'rgba(72, 84, 191, 0.7)' }, { color: 'rgba(222, 249, 47, 0.7)' }
];
let result=[];
const n = performance.now();
for(let i=0;i<data.length;i++){
result.push(Object.assign(data[i], colors[i]))
}
const n2 = performance.now();
console.log(n2 - n);
const n3 = performance.now();
const results = data.map((o,i)=>Object.assign(o, colors[i]))
const n4 = performance.now();
console.log(n4 - n3);