javascript:重命名API对象的键

时间:2019-04-17 14:45:11

标签: javascript

我从API获得以下数据数组。

[
    {
        "barCode": "31568308949"
        "itemDesc": "ASHTON-250"
        "permPrice": 19.99
    }
]

预期结果如下。

[
    {
        "Bar Code": "31568308949"
        "Item Description": "ASHTON-250"
        "Prem Price": 19.99
    }
]

有人可以帮助我实现这一目标吗?预先感谢。

9 个答案:

答案 0 :(得分:5)

如果始终是这3个字段,则只需对其进行显式重命名。

let input = [{'barCode': '31568308949', 'itemDesc': 'ASHTON-250', 'permPrice': 19.99}];

let output = input.map(x => ({
  'Bar Code': x.barCode,
  'Item Description': x.itemDesc,
  'Prem Price': x.permPrice,
}));

console.log(output);

答案 1 :(得分:2)

另一种解决方案是创建一个keyMap,您可以在其中添加新密钥,它会动态映射您添加的任何新密钥:

let keyMap = {
    barCode: "Bar Code",
    itemDesc: "Item Description",
    permPrice: "Prem Price"
};

let input = [{ "barCode": "31568308949", "itemDesc": "ASHTON-250", "permPrice": 19.99 }];

let newData = input.map(obj => {
    return Object.keys(obj).reduce((prev, next) => {
        if (next in keyMap) {
            prev[keyMap[next]] = obj[next];
        } else {
            prev[next] = obj[next];
        }

        return prev;
    }, {});
});

console.log(newData);

答案 2 :(得分:1)

您可以使用地图功能并删除运算符。

var a = [ { "barCode": "31568308949", "itemDesc": "ASHTON-250", "permPrice": 19.99 } ];

var c = a.map(b=> {

b["Bar Code"] = b.barCode;
b["Item Description"] = b.itemDesc;
b["Prem Price"] = b.permPrice; 
delete b.barCode;
delete b.itemDesc;
delete b.permPrice;
return b;

})
console.log(c)

var a = [ { "barCode": "31568308949", "itemDesc": "ASHTON-250", "permPrice": 19.99 } ];

var c = a.map(b=> {

b["Bar Code"] = b.barCode;
b["Item Description"] = b.itemDesc;
b["Prem Price"] = b.permPrice; 
delete b.barCode;
delete b.itemDesc;
delete b.permPrice;
return b;

})


console.log(c)

答案 3 :(得分:1)

您可以使用map遍历数组。使用Object.entries将对象转换为字符串。制作第一个关键大写字母并拆分关键购买大写字母。通过空间连接并将其用作对象,以形成所需的对象

let arr = [{
  "barCode": "31568308949",
  "itemDesc": "ASHTON-250",
  "permPrice": 19.99
}]

let result = arr.map(o => {
  return Object.entries(o).reduce((c, [k, v]) => {
    let x = k[0].toUpperCase() + k.slice(1).match(/[a-z]+|[A-Z]+[a-z]*/g).join(" ");
    c[x] = v;
    return c;
  }, {});
})

console.log(result);

答案 4 :(得分:1)

如果您尝试更改收到的对象,则可以在数据数组中使用map function,如下例所示:

var elements = [ 
      { "barCode": "31568308949", "itemDesc": "ASHTON-250", "permPrice": 19.99 }, 
      { "barCode": "31568308950", "itemDesc": "ASH-299",    "permPrice": 29.99 } 
    ];

function convertItem(item) {
    var newItem = {'Bar Code':item.barCode,
                  'Item Description': item.itemDesc,
                  'Prem Price': item.permPrice};
    return newItem;
 }

  elements.map(converItem);

答案 5 :(得分:1)

通常,要执行此操作,您可以使用replace()创建一个正则表达式,以拆分密钥并使用它们来创建新对象:

let o = { "someReallyLongKey": 1, "barCode": "31568308949", "itemDesc": "ASHTON-250", "permPrice": 19.99 }

let newObj = Object.entries(o).reduce((obj, [k, v]) => {
    let newKey = k.replace(/([a-z])([A-Z])/g, '$1 $2').replace(/\b\w/g, w => w.toUpperCase())
    obj[newKey] = v
    return obj
    }, {})
console.log(newObj)

如果两个正则表达式成为瓶颈,则可以将它们组合成一个replace(),但是我认为这更容易阅读和理解。

答案 6 :(得分:1)

如果您能够使用某些浏览器的较新版本支持的新建议Object.fromEntries(),并假设来自integer的对象@Override public User save(UserDto user) throws Exception { User newUser = new User(); newUser.setUsername(user.getUsername()); newUser.setPassword(bcryptEncoder.encode(user.getPassword())); newUser.setAge(user.getAge()); newUser.setSalary(user.getSalary()); newUser.setRole(user.getRole()); // here is the problem try { userDao.save(newUser); } catch (Exception e) { throw new Exception(e); } return newUser; } 位于{{3}中}格式,那么您可以执行以下操作:

keys
API

答案 7 :(得分:1)

将其分为两个步骤,一个步骤将lowerCamelCase转换为Upper Title Case,而另一个步骤则使用函数转换对象的键,产生如下代码:

const titleCase = str =>
  str.replace(/([^A-Z])([A-Z])/g, (_, x, y) =>  x + ' ' + y.toUpperCase())
     .replace(/^./, x => x.toUpperCase())

const convertKeys = (fn) => (obj) => Object.entries(obj).reduce(
  (a, [k, v]) => ({...a, [fn(k)]: v}),
  {}
)

const transform = convertKeys(titleCase)

const apiResponse = [
    {
        "barCode": "31568308949",
        "itemDesc": "ASHTON-250",
        "permPrice": 19.99
    }
]

console.log(apiResponse.map(transform))

当然,如果仅用于少数几个固定字段,则显式地编写它会更容易。

答案 8 :(得分:0)

这将使用重命名之类的新键动态创建一个新对象

function objectMap(source,keyMap) {
    return Object.entries(keyMap).reduce((o,[key , newKey]) => {
            o[newKey]=source[key]
            return o;},{})
}

作为与api一起使用的示例

 keyMap = {
  "barCode":"Bar Code",
  "itemDesc": "Item Description"
  "permPrice": "Prem Price"
 }

 this.post('http://..','{}').pipe(map(result) => result.map(item) => objectMap(item,keyMap))

rename js object keys