![](/img/trans.png)
[英]How to concat 2 JavaScript arrays into a new array that is a combination of those two?
[英]How to concat two JS arrays to a new array of objetcs as key: value?
我們有2個數組,例如:
foo = ['one', 'two', 'three']
bar = ['morning', 'day', 'night']
我如何獲得一個新的對象數組,它應該像這樣:
obj = [{'one': 'morning'}, {'two': 'day'}, {'three': 'night'}]
提前致謝!
沒有標准功能執行此操作。
我會這樣做:
var list = {};
for(var i = 0; i < foo.length(); ++i) {
list[foo[i]] = bar[i];
}
也許您應該做一些安全性工作,例如if(bar [i])等。
更安全的是:
var list = {};
var len = Math.min(foo.length(), bar.length());
for(var i = 0; i < len; ++i) {
if(!list[foo[i]]) {
list[foo[i]] = bar[i];
}
}
只需遍歷數組並將鍵/值對加載到對象中即可。
var foo = ['one', 'two', 'three'],
bar = ['morning', 'day', 'night'],
obj = {},
i;
for (i = 0; i < foo.length; i++) {
obj[foo[i]] = bar[i];
}
現在你應該有
obj = [{'one': 'morning'}, {'two': 'day'}, {'three': 'night'}]
注意:此解決方案假定兩個數組的長度相同。
所以也許這種方法適合您
Array.prototype.join_array = function(keys, val){
if (arguments.length < 2 ) return {};
for (var i = 0; i < keys.length ; i++ ){
var o = {};
o[ keys[i] ] = val[i] || val[val.length -1];
this.push( o );
}
};
var a = [];
a.join_array( ['key1', 'key2'], ['val1', 'val2'] );
console.log( JSON.stringify(a) );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.