1

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.

  • 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 Apr 17 at 14:47
  • Well what is it you are trying to achieve – Isaac Vidrine Apr 17 at 14:49
  • What have you tried so far? – Scott Sauyet Apr 17 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 Apr 17 at 14:57
  • Thanks Everybody – aman jain Apr 17 at 15:24
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);

  • Thanks @junvar... – aman jain Apr 17 at 15:23
2

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

  • thanks @Daniel .. – aman jain Apr 17 at 15:21
1

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)

  • 1
    Thanks Hien Nguyen – aman jain Apr 17 at 15:25
1

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

  • Thanks @Eddie .. – aman jain Apr 17 at 15:22
1

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

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 combine them into a single replace(), but I think this is much easier to read and understand.

  • Thanks Mark Meyer – aman jain Apr 17 at 15:22
1

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.

  • Thanks Scott Sauyet – aman jain Apr 17 at 15:22
1

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 coming 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;}

  • Thanks Shidersz – aman jain Apr 17 at 15:22
  • @amanjain You're welcome. Anyway, you can give an up-vote to those answers that where useful to you and choice the most you like as the accepted one. – Shidersz Apr 17 at 15:27
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

  • Thanks @malbarmawi – aman jain Apr 17 at 15:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.