簡體   English   中英

我目前正在研究 Javascript 並堅持在對象中使用 for 循環

[英]I am currently working on Javascript and stuck with using for loop in objects

[ { name: 'rajesh',
    type: 'varchar',
    length: 50,
    value: '07/21/2020' },
  { name: 'ramesh',
    type: 'varchar',
    length: 50,
    value: '07/21/2020' },
  { name: 'abhi', type: 'int', value: '5' }
 ]
  1. 我需要使用 for 循環
  2. 我需要像這樣的 output('rajesh':'07/21/2020,'ramesh':'07/21/2020','abhi': 5
  3. 需要使用JSON.stringify

可能是這樣的,

 const data = [{ name: 'rajesh', type: 'varchar', length: 50, value: '07/21/2020' }, { name: 'ramesh', type: 'varchar', length: 50, value: '07/21/2020' }, { name: 'abhi', type: 'int', value: '5' } ] const convertedData = Object.fromEntries(data.map(({ name, value }) => [name, value])) console.log(convertedData) console.log(JSON.stringify(convertedData))

采取的步驟:

  • data轉換為 touple(使用Object.fromEntries進行轉換)
  • 從 touples 創建 Object
  • 轉換為 JSON

嘗試這個

 let arr = [ { name: 'rajesh', type: 'varchar', length: 50, value: '07/21/2020' }, { name: 'ramesh', type: 'varchar', length: 50, value: '07/21/2020' }, { name: 'abhi', type: 'int', value: '5' } ]; let result = {}; for(i= 0; i < arr.length; i++){ result[arr[i].name] = arr[i].value; } console.log(result); console.log(JSON.stringify(result));

我相信這就是您正在尋找的:

 const data = [ { name: 'rajesh', type: 'varchar', length: 50, value: '07/21/2020' }, { name: 'ramesh', type: 'varchar', length: 50, value: '07/21/2020' }, { name: 'abhi', type: 'int', value: '5' } ] const result = data.reduce((acc, curr) => { acc[curr.name] = curr.value return acc }, {}) console.log(result, JSON.stringify(result))

let arr = [ { name: 'rajesh',
    type: 'varchar',
    length: 50,
    value: '07/21/2020' },
  { name: 'ramesh',
    type: 'varchar',
    length: 50,
    value: '07/21/2020' },
  { name: 'abhi', type: 'int', value: '5' }
 ];


 let result = {};

 for(i= 0; i < arr.length; i++){
    result[arr[i].name] = arr[i].value;
 }

 console.log(result);
 console.log(JSON.stringify(result));

 const data = [{ name: 'rajesh', type: 'varchar', length: 50, value: '07/21/2020' }, { name: 'ramesh', type: 'varchar', length: 50, value: '07/21/2020' }, { name: 'abhi', type: 'int', value: '5' } ] const convertedData = Object.fromEntries(data.map(({ name, value }) => [name, value])) console.log(convertedData) console.log(JSON.stringify(convertedData))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM