2017-08-08 64 views
1
var temparray1 = [[1,3,4],[5,6,7],[8,9,10]]; 
var final = []; 
var obj = {}; 
for(var temp in temparray1){ 
    for(var test in temparray1[temp]){ 
     obj.b = temparray1[temp][0]; 
     obj.c = temparray1[temp][1]; 
     obj.d = temparray1[temp][2]; 
    } 
    console.log(obj); 
    final.push(obj); 
} 

電流輸出的Array.push(對象)在循環結束在JavaScript不推

[{ b: 8, c: 9, d: 10 } 
{ b: 8, c: 9, d: 10 } 
{ b: 8, c: 9, d: 10 }] 

進出料口把

[{ b: 1, c: 3, d: 4 } 
{ b: 5, c: 6, d: 7 } 
{ b: 8, c: 9, d: 10 }] 

我運行我的javascript in node.js -v 8.1.x服務器

在for循環結束時在控制檯中打印所需的輸出,但不在陣列中推

+2

切勿使用'爲..in'循環遍歷數組和'obj'是不是在你的代碼中定義的? – adeneo

+0

是obj = {}已經宣佈,但我可能知道爲什麼..in不可能這是我認爲的正常迭代 – muthukumar

回答

1

var temparray = [[1, 3, 4], [5, 6, 7], [8, 9, 10]]; 
 
const final = temparray.map(a => ({ b: a[0], c: a[1], d: a[2] })); 
 

 
console.log(final);

+0

它幫助了我@Erazihel謝謝 – muthukumar

1

很可能您在for循環之外設置了obj,因此道具被覆蓋,並且您多次推送相同的對象進入陣列。只需將obj聲明移入循環。你可能只需要外部循環。

順便說一句短得多:

let final = temparray1.map(
([b,c,d]) => ({b,c,d}) 
); 
1

這裏是你想要的東西

var temparray1 = [[1,3,4],[5,6,7],[8,9,10]]; 
var final = []; 
for(var temp in temparray1){ 
    var obj = {}; 
    obj['b'] = temparray1[temp][0]; 
    obj['c'] = temparray1[temp][1]; 
    obj['d'] = temparray1[temp][2]; 
    final.push(obj); 
} 
console.log(final); 

希望這有助於!

+0

你得到什麼錯誤?我可以給你一個實例,如果你想要它 – zenwraight

+0

@Jonasw在這裏 - https://repl.it/KBxG ...試試吧,讓我知道 – zenwraight

+0

上面的代碼只推動最後一次array [{ b:8,c:9,d:10} {b:8,c:9,d:10} {b:8,c:9,d:10}] @zenwraight array.map函數是正確的apporach – muthukumar

1

你可以使用Array#map並與想要的屬性返回一個對象。

var array = [[1, 3, 4], [5, 6, 7], [8, 9, 10]], 
 
    result = array.map(function (a) { 
 
     return { b: a[0], c: a[1], d: a[2] }; 
 
    }); 
 
    
 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

隨着ES6,你可以映射內的陣列以及有用於與Object.assignspread syntax ...鍵陣列。

var array = [[1, 3, 4], [5, 6, 7], [8, 9, 10]], 
 
    keys = ['b', 'c', 'd'], 
 
    result = array.map(a => Object.assign(...keys.map((k, i) => ({ [k]: a[i] })))); 
 
    
 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }