admin管理员组

文章数量:1312635

I have the following data array from a API.

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

And expected result as below.

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

Could anybody help me to achieve this. Thanks in advance.

I have the following data array from a API.

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

And expected result as below.

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

Could anybody help me to achieve this. Thanks in advance.

Share Improve this question edited Apr 17, 2019 at 15:20 Diogo Calazans 4989 silver badges18 bronze badges asked Apr 17, 2019 at 14:45 aman jainaman jain 1751 gold badge1 silver badge7 bronze badges 6
  • 1 so, you want to change what the API sends you? Or did you want to change the data once you receive it? – Jaromanda X Commented Apr 17, 2019 at 14:47
  • Well what is it you are trying to achieve – Isaac Vidrine Commented Apr 17, 2019 at 14:49
  • What have you tried so far? – Scott Sauyet Commented Apr 17, 2019 at 14:52
  • x.map(o=>Object.entries(o).reduce((a,[k,v])=>(a[{barCode:'Bar Code',itemDesc:'Item Description',permPrice:'Perm Price'}[k]]=v,a),{})); – Jaromanda X Commented Apr 17, 2019 at 14:57
  • Thanks Everybody – aman jain Commented Apr 17, 2019 at 15:24
 |  Show 1 more ment

9 Answers 9

Reset to default 5

If it's always these 3 fields, then simply rename them explicitly.

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);

Another solution is to create a keyMap where you can just add new keys and it will dynamically map any new keys you add:

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);

You can use map function and delete operator for this requirement.

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)

You can use map to loop thru the array. Use Object.entries to convert the object into a string. Make the first key capital letter and split the key buy capital letter. Join by space and use it as the ey to form the desired object,

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);

If you trying to change the object that you received, you could use the map function in your array of data like this example below:

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);

To do this in a general case you can make a regex with replace()that splits your keys and use them to create a new object:

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)

If two regexes is a bottleneck, you may be able to bine them into a single replace(), but I think this is much easier to read and understand.

Breaking this down into two steps, one which converts from lowerCamelCase to Upper Title Case and one which converts the keys of an object using a function, yields code like this:

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))

Of course if it's just for those few fixed fields, it's easier just to write this explicitly.

If you are able to use the new proposal Object.fromEntries() supported on newer versions of some browsers, and assuming the keys of the objects ing from the API are in lowerCamelCase format, then you can do something like this:

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

let res = input.map(
    o => Object.fromEntries(Object.entries(o).map(
      ([k, v]) => ([k[0].toUpperCase() + k.slice(1).replace(/([A-Z])/g, ' $1'), v])
    ))
);

console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

this will dynamically create a new object with the new keys like renaming

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

as an example of using this with 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

本文标签: javascript Rename the Keys of API objectStack Overflow