2017-03-23 8 views
0

変数にDestructingを使用しようとしています。 MDNの例を使用して:Javascript - 破棄された項目を新しい変数に入れる

var people = [ 
    { 
     name: 'Mike Smith', 
     family: { 
      mother: 'Jane Smith', 
      father: 'Harry Smith', 
      sister: 'Samantha Smith' 
     }, 
     age: 35 
    }, 
    { 
     name: 'Tom Jones', 
     family: { 
      mother: 'Norah Jones', 
      father: 'Richard Jones', 
      brother: 'Howard Jones' 
    }, 
     age: 25 
    } 
]; 

for (var {name: n, family: {father: f}} of people) { 
    console.log('Name: ' + n + ', Father: ' + f); 
    //Put results into a variable here 
} 

// "Name: Mike Smith, Father: Harry Smith" 
// "Name: Tom Jones, Father: Richard Jones" 

上記は2つの行をループで分割します。私が望むのは、for-inループの結果が新しい変数に戻され、Express.jsを使ってクライアントに送ることができるようにすることです。

+0

...ので、それを行います。あなたは質問がありましたか? [良い質問をする方法](http://stackoverflow.com/help/how-to-ask)を参照して、やり直してください。 – Hamms

+0

ここでは、varを破壊することとは関係ありません。質問のタイトルは間違っています。新しく構造化されたデータを配列に入れて、AJAXまたはsthを使用してサーバーに送り返してください – NDFA

答えて

1

私はあなただけの配列(または何でも)にそれをプッシュする必要があり、正しくあなたの質問を理解していた場合:

var people = [ 
    { 
     name: 'Mike Smith', 
     family: { 
      mother: 'Jane Smith', 
      father: 'Harry Smith', 
      sister: 'Samantha Smith' 
     }, 
     age: 35 
    }, 
    { 
     name: 'Tom Jones', 
     family: { 
      mother: 'Norah Jones', 
      father: 'Richard Jones', 
      brother: 'Howard Jones' 
    }, 
     age: 25 
    } 
]; 

var results = [] 

for (var {name: name, family: {father: father}} of people) { 
    results.push({ name, father }) 
} 

console.log(JSON.stringify(results)); 
// => [{"name":"Mike Smith","father":"Harry Smith"},{"name":"Tom Jones","father":"Richard Jones"}] 

https://jsfiddle.net/bcLour92/1/

1

あなたは次のことを試すことができます。

let results = []; 
for (var {name: n, family: {father: f}} of people) { 
    const result = 'Name: ' + n + ', Father: ' + f; 
    console.log(result); 
    results.push(result); 
    //Put results into a variable here 
} 
console.log('results', results); 

この時点で、あなたは今、あなたは結果のこの配列でやりたいことができます。

関連する問題