簡體   English   中英

循環通過 object 並將值添加到 Javascript object 以增量計數作為鍵

[英]Looping through an object and adding values to a Javascript object with the incremental count as the key

例子:

{
 Do you have a monthly student payment?: 133, 
 Do you have a monthly car loan payment?: 150,
 Do you have a monthly car insurance payment?: 120,
 How much do you estimate you spend on gas for your car monthly?: 150
}

Output: {120: 1, 133: 1, 150: 1}

預期 output:

{1: 133, 2: 150, 3: 120 , 4: 150}

我的 function:

  getClicked() {
    this.newObj = {};
    this.mortgageRateFound = [];
    for (let key in this.numbersInForm) {
      console.log(this.numbersInForm)
      if (! this.newObj[this.numbersInForm]) {
        this.newObj[this.numbersInForm[key]] = (this.newObj[key]+1) || 1
      }
    }
    console.log(this.newObj);
  }

您可以使用Object.values來獲取 object 中每個鍵的值,然后Array.map使用數組索引 (+1) 作為對象數組然后,您可以使用Object.assign將該對象數組展平為單個 object:

 const obj = { "Do you have a monthly student payment?": 133, "Do you have a monthly car loan payment?": 150, "Do you have a monthly car insurance payment?": 120, "How much do you estimate you spend on gas for your car monthly?": 150 }; const out = Object.assign({}, ...Object.values(obj).map((v, i) => ({ [i+1]: v }))); console.log(out);

ES5

 const obj = { "Do you have a monthly student payment?": 133, "Do you have a monthly car loan payment?": 150, "Do you have a monthly car insurance payment?": 120, "How much do you estimate you spend on gas for your car monthly?": 150 }; var output = Object.keys(obj).reduce(function(acc, curr, index) { acc[index] = obj[curr] return acc; }, {}) console.log(output)

暫無
暫無

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

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