繁体   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