如何在map函数内部传递对象?

时间:2018-12-11 10:15:33

标签: javascript jquery

我有一个如下的临时数组:

10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {name: "john", address: "a1", v1: 11.972646011733632, …}
1: {name: "Dave", address: "a2", v1: 11.972646011733632, …}
2: {name: "Sid", address: "a3", v1: 11.972646011733632, …}

我有一个对象来检查该字段是否需要格式化

obj = {
    name: [],
    address: [],
    v1: ['round', 'percentage'],
    v2: ['round', 'percentage'],
    year: []
};

我需要的是在临时循环上检查obj中是否有键,并且是否有舍入和百分比,然后将第一轮舍入到小数点后两位并添加'%'。

我希望输出如下:

0: {name: "john", address: "a1", v1: 11.97%, …}
1: {name: "Dave", address: "a2", v1: 16.47%, …}
2: {name: "Sid", address: "a3", v1: 11.37%, …}

3 个答案:

答案 0 :(得分:2)

您可以结合使用mapreduce方法来返回新的对象数组,然后使用switch来更改obj中每个数组字段的值。

const data = [{name: "john", address: "a1", v1: 11.972646011733632},
{name: "Dave", address: "a2", v1: 11.972646011733632},
{name: "Sid", address: "a3", v1: 11.972646011733632}]

const obj = {
  name: [],
  address: [],
  v1: ['round', 'percentage'],
  v2: ['round', 'percentage'],
  year: []
};

const result = data.map(o => {
  return Object.entries(o).reduce((r, [k, v]) => {
    if (obj[k] && obj[k].length) {
      obj[k].forEach(field => {
        switch (field) {
          case 'round':
            v = Math.round(v * 100) / 100
            break;
          case 'percentage':
            v += '%'
            break;
        }
      })
    }
    r[k] = v;
    return r
  }, {})
})

console.log(result)

答案 1 :(得分:1)

您可以通过以下方式概括对象中某些键的格式。

System.Xml.Serialization

答案 2 :(得分:-1)

请尝试使用此代码。

var obj = {0: {name: "john", address: "a1", v1: 11.972646011733632, v2: 32.35345132541},1: {name: "Dave", address: "a2", v1: 15.972646011733632, v2: 12.35345132541},2: {name: "Sid", address: "a3", v1: 22.972646011733632, v2: 42.35345132541}};
    var length = Object.keys(obj).length;
    for (var i = 0; i < length; i++) {
        obj[i].v1 = parseFloat(Math.round(obj[i].v1 * 100) / 100).toFixed(2) + ' %';
        obj[i].v2 = parseFloat(Math.round(obj[i].v2 * 100) / 100).toFixed(2) + ' %';
    }   
    console.log(obj);

享受!!