在数组中每个大写字母后合并一个空格

时间:2018-07-03 07:31: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原始格式

3 个答案:

答案 0 :(得分:0)

map将每个项目更改为一个新项目,遍历条目并适当地替换键:

var items = [{
    "BrandConstruct": 165,
    "YearPlanData": "a"
  },
  {
    "BrandConstruct": 236,
    "YearPlanData": "c"
  },
  {
    "BrandConstruct": 376,
    "YearPlanData": "b"
  }
];
const addSpaces = str => str.replace(/(.)([A-Z])/g, '$1 $2');
const newItems = items.map(item => (
  Object.entries(item).reduce(
    (a, [key, val]) => Object.assign(a, { [addSpaces(key)]: val }),
    {}
  )
));
console.log(newItems);

答案 1 :(得分:0)

使用Array.map遍历每个对象,并使用Array.reduce和Regex创建一个新对象

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

items = items.map(o => Object.entries(o).reduce((a,[k,v]) => Object.assign(a, {[k.replace(/([a-z](?=[A-Z]))/g, '$1 ')] :v}), {}));
console.log(items);

答案 2 :(得分:0)

使用RegExp()split()可以做到这一点:

var items = [
  {
      "BrandConstruct": 165,
      "YearPlanData": "a"
  },
  {
      "BrandConstruct": 236,
      "YearPlanData": "c"
  },
  {
      "BrandConstruct": 376,
      "YearPlanData": "b"
  }
];
var res = items.map((item) => {
  var keys = Object.keys(item);
    keys.forEach((key)=>{
    var newKey = key.split(/(?=[A-Z])/);
    item[newKey.join(' ')] = item[key];
    delete item[key];
  });
  return item;
  
});
console.log(res);