2016-03-03 53 views
-1

除了迭代未關聯的數組並手動添加它們外,如何合併具有序列化的名稱/值對的未關聯數組?合併與序列化的名稱/值對的未關聯數組

//I select some values 
var data = $('#mytable input:checked'); 
console.log(data); //Object[input attribute value = "1", input attribute value = "3"] 

//I get some extra values I wish to send to the server 
var types = data.map(function() { 
    return $(this).data("types"); 
}).get(); 
console.log(types); // ["type1", "type3"] 

//I serialize data 
data = data.serializeArray(); 
console.log(data); // [Object { name="id[]", value="1"}, Object { name="id[]", value="3"}] 

//I add an extra value 
data.push({ 
    name: "task", 
    value: 'restoreRecord' 
}) 
console.log(data); // [Object { name="id[]", value="1"}, Object { name="id[]", value="3"}, Object { name="task", value="restoreRecord"}] 

/* 
How do I merge data and types so that I come up with the following: 
[ 
Object { name="id[]", value="1"}, 
Object { name="id[]", value="3"}, 
Object { name="types[]", value="type1"}, 
Opject { name="types[]", value="type3"}, 
Object { name="task", value="restoreRecord"} 
] 
*/ 

回答

0

您可以通過types for循環運行,並從中增加值data

// I want to merge this 
var data = [{ 
    name: "id[]", 
    value: "1" 
}, { 
    name: "id[]", 
    value: "3" 
}, { 
    name: "task", 
    value: "restoreRecord" 
}]; 

// with this 
var types = ['type1', 'type2']; 

for(var i = 0; i < types.length; i++){ 
    data.push({ 
     name: 'types[]', 
     value: types[i] 
    }); 
} 
console.log(data); 
+0

我是在當你回答沒有說​​明循環權的過程。 – user1032531

+0

不知道是否有某種以jQuery方式烘焙的方式。 – user1032531