循环遍历一个对象并将值添加到以增量计数为键的 Javascript 对象

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
}

输出:{120: 1, 133: 1, 150: 1}

预期输出:

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

我的函数:

  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 to get the values for each key in the object, then Array.map that to an array of objects using the array index (+1) as the key. You can then use Object.assign 将该对象数组展平为单个对象:

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);

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)