在数组项中添加空间

时间:2018-06-28 12:52:07

标签: javascript jquery

我有一个包含键值对项的数组,我想在每个大写字母后的每个键中添加空格。

var items = [
    {
        "BrandConstruct": 165,
        "YearPlanData": "a"
    },
    {
        "BrandConstruct": 236,
        "YearPlanData": "c"
    },
    {
        "BrandConstruct": 376,
        "YearPlanData": "b"
    }

]

上面是我的数组,我想要它如下:-

 var items = [
    {
        "Brand Construct": 165,
        "Year Plan Data": "a"
    },
    {
        "Brand Construct": 236,
        "Year Plan Data": "c"
    },
    {
        "Brand Construct": 376,
        "Year Plan Data": "b"
    }

]

再一次我想用javascript原始格式

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

var result = items.map(o => {                          //Loop thru the array using map
  return Object.entries(o).reduce((c, [k, v]) => {     //Convert the object into an array using Object.entries | Use reduce to group the array
    return Object.assign(c, {                          //Use Object.assign to create new object
      [k.split(/(?=[A-Z])/).join(" ")]: v              //Use regex to split the key by capital letter and join
    })
  }, {});
});

这是一个代码段(较短的版本):

var items = [{"BrandConstruct":165,"YearPlanData":"a"},{"BrandConstruct":236,"YearPlanData":"c"},{"BrandConstruct":376,"YearPlanData":"b"}]
var result = items.map(o => Object.entries(o).reduce((c, [k, v]) => Object.assign(c, {[k.split(/(?=[A-Z])/).join(" ")]: v}), {}));

console.log(result);

您可以使用Object.keys()来兼容Angular和IE9:

var items = [{"BrandConstruct":165,"YearPlanData":"a"},{"BrandConstruct":236,"YearPlanData":"c"},{"BrandConstruct":376,"YearPlanData":"b"}];

var result = items.map(function(o) {
  return Object.keys(o).reduce(function(c, k) {
    c[k.split(/(?=[A-Z])/).join(" ")] = o[k];
    return c;
  }, {})
});

console.log(result);