2016-08-05 44 views
2

我想在一個對象合併多個陣列的值,以一個陣列是這樣的:Jquery的陣列融合

[1,2,3] 
[4,5,6] 

到:

[ 
    {name: 1, value: 4}, 
    {name: 2, value: 5}, 
    {name: 3, value: 6} 
] 
+1

你嘗試過這麼遠嗎? StackOverflow不是'爲我編碼的網站'。 –

回答

0

使用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);

0

您可以在一個陣列上使用一個簡單的循環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);

0
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); 
+0

我認爲這樣循環一個數組並不是個好主意!每當使用'for ... in'時,你都應該牢記這一點:http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-a-bad-idea – eisbehr

+0

好吧,我會記住 – Tuhin

+0

現在你已經記住了,你應該刪除這個答案,因爲它通常是*不好的做法*,應該避免任何地方。 ;) – eisbehr

0

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);

0

或PHP :)

<?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>'; 
?> 
+0

儘管這段代碼可以解決這個問題,但[包括解釋](// meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)確實有助於提高您的帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。也請儘量不要使用解釋性註釋來擠佔代碼,因爲這會降低代碼和解釋的可讀性! – FrankerZ