【发布时间】:2016-08-05 07:31:01
【问题描述】:
我想将一个对象中多个数组的值合并到一个数组中,如下所示:
[1,2,3]
[4,5,6]
收件人:
[
{name: 1, value: 4},
{name: 2, value: 5},
{name: 3, value: 6}
]
【问题讨论】:
-
到目前为止您尝试过什么? StackOverflow 不是“为我编写代码”的网站。
我想将一个对象中多个数组的值合并到一个数组中,如下所示:
[1,2,3]
[4,5,6]
收件人:
[
{name: 1, value: 4},
{name: 2, value: 5},
{name: 3, value: 6}
]
【问题讨论】:
使用Array#map方法在现有的基础上创建一个新数组。
var a = [1, 2, 3],
b = [4, 5, 6];
// iterate over array `a` to genearate object array
var res = a.map(function(v, i) {
// generate object ( result array element )
return {
name: v, // name from array `a`
value: b[i] // value from array `b` get using index
};
})
console.log(res);
【讨论】:
您可以在一个数组上使用简单的for 循环,然后根据自己的喜好创建结果。
var names = [1, 2, 3],
values = [4, 5, 6],
result = [];
for( var i = 0; i < names.length; i++ ) {
result.push({
name: names[i],
value: values[i]
});
}
console.log(result);
【讨论】:
var names = [1,2,3];
var values = [4,5,6];
var result =[];
for(var i=0;i<names.length;i++){
var obj= {
"name":names[i],
"value": values[i]
}
result.push(obj);
}
console.log(result);
【讨论】:
for ... in,你都应该牢记这一点:stackoverflow.com/questions/500504/…
arr1 = [1,2,3];
arr2 = [4,5,6];
//prepare array to fill
obj = [];
// for every item we merge them into an object and pass them into the newObj
function merge(item, index, arr2, newObj){
temp = {};
temp[item] = arr2[index];
newObj.push(temp);
}
//give the item as key, the index for the second array, and the object we want to fill
arr1.forEach((item, index) => merge(item, index, arr2, obj));
console.log(obj);
【讨论】:
PHP 中的 OR :)
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
$names = array('Chevalier','Sorcier','Archer');
$values = array('5','6','8');
$fusion = array();
for($i=0; $i<count($names); $i++){
$fusion[$names[$i]] = $values[$i];
}
echo '<pre>';
print_r($names);
print_r($values);
print_r($fusion);
echo '</pre>';
?>
【讨论】: