【问题标题】:How can you multiply a value from an Object.entry for another key value inside a loop?如何将 Object.entry 中的值与循环内的另一个键值相乘?
【发布时间】:2021-06-12 20:30:41
【问题描述】:

我想为每个部门添加不同的工作人员值,但将该值乘以另一个 key:value 属性。这是一个 Vue.js 组合 API webapp。

export default {
  setup( props, {emit}) { 
  let data = reactive({

  let chosenCompanies:  [
        { id: 'Big',  workers: 250, clones: 9 },
        { id: 'Medium', workers: 75, clones: 2 },
        { id: 'Small', workers: 10, clones: 6 },
        { id: 'Individual', workers: 1, clones: 7}
      ]
});
const employedWorkers = () => {
  let employedworkersPrivate = 0;
  data.chosenCompanies.forEach(function(sector){
    for (const [key, value] of Object.entries(sector)) {
        if (key === 'workers') {
          employedworkersPrivate += parseInt(value)
       
  //  I need to multiply the number of workers per clones here, instead of just adding more workers 
  // can I get to the key 'clones' value here?

          }
    }
  })
  return employedworkersPrivate
}
}
}

【问题讨论】:

  • 谢谢你,但我做了,只是我清理代码时忘记粘贴了

标签: javascript function loops vue.js vue-composition-api


【解决方案1】:

无需遍历条目 - 只需访问您需要的确切两个键,.workers.clones

let chosenCompanies =  [
        { id: 'Big',  workers: 250, clones: 9 },
        { id: 'Medium', workers: 75, clones: 2 },
        { id: 'Small', workers: 10, clones: 6 },
        { id: 'Individual', workers: 1, clones: 7}
      ]

const employedWorkers = () => {
  let employedworkersPrivate = 0;
  chosenCompanies.forEach(function(sector) {
    employedworkersPrivate += sector.workers * sector.clones;
  });
  return employedworkersPrivate;
};

console.log(employedWorkers());

【讨论】:

  • 不幸的是,我认为我这样做了,因为我使用的是 Vue.js,并且 selectedCompanies 是一个代理......我认为这没有什么区别,所以我没有提到。
  • 新编辑的代码let data = reactive({ let chosenCompanies = [的语法无效,你可以粘贴你的实际代码吗?但是,如果您在回调中迭代 chosenCompanies,它看起来不像 chosenCompanies 将是一个代理,它是一个数组
【解决方案2】:

您只需要遍历chosenCompanies 并从每个sector 访问这些值:

const chosenCompanies =  [
  { id: 'Big',  workers: 250, clones: 9 },
  { id: 'Medium', workers: 75, clones: 2 },
  { id: 'Small', workers: 10, clones: 6 },
  { id: 'Individual', workers: 1, clones: 7}
];
let employedworkersPrivate = 0;

chosenCompanies.forEach(function(sector){
  employedworkersPrivate += sector.workers * sector.clones;
});

console.log(employedworkersPrivate);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-04
    • 2019-07-06
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    • 2015-12-05
    • 1970-01-01
    相关资源
    最近更新 更多