2

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.

Diogo Calazans
  • 488
  • 9
  • 18
aman jain
  • 165
  • 1
  • 1
  • 7

9 Answers9

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);
junvar
  • 11,151
  • 2
  • 30
  • 46
4

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);
Daniel
  • 10,641
  • 12
  • 47
  • 85
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)
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
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);
Eddie
  • 26,593
  • 6
  • 36
  • 58
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);
Diogo Calazans
  • 488
  • 9
  • 18
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.

Mark
  • 90,562
  • 7
  • 108
  • 148
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;}
Shidersz
  • 16,846
  • 2
  • 23
  • 48
  • @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 '19 at 15:27
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.

Scott Sauyet
  • 49,207
  • 4
  • 49
  • 103
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

Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91