Jeremy Ragsdale
Jeremy Ragsdale

Reputation: 95

Rename JSON Keys based on first "row" in object array

I have a JSON object array where I need to rename the keys based on values in the first object. Trying to do this in NodeJS but not having any luck.

I could probably brute force it with a couple of loops but was hoping for a more scalable solution since the number of "columns" change from time to time.

Here is an example

[{"A" : "Key1", "B" : "Key2", "C" : "Key3"},
 {"A" : "Data1", "B" : "Data2", "C" : "Data3"},
 {"A" : "Data5", "B" : "Data5", "C" : "Data7"}]

I would like the result to be like

[{"Key1" : "Key1", "Key1" : "Key2", "Key1" : "Key3"},
 {"Key1" : "Data1", "Key2" : "Data2", "Key3" : "Data3"},
 {"Key1" : "Data5", "Key2" : "Data5", "Key3" : "Data7"}]

Upvotes: 0

Views: 633

Answers (3)

Luis Maracara Cruz
Luis Maracara Cruz

Reputation: 36

Lets say the old array is stored in a var called oldArray:

var keys = Object.keys(oldArray[0]); // get first object keys
var newArray = oldArray.map(function(obj,index){
// Iterate over each object to replace keys
if(index === 0) return obj; /* if first object we dont need to replace 
keys */
var objKeys = Object.keys(obj); //old keys for reference only
  return Object assign({},{
      [keys[0]]: obj[objKeys[0],  // assigning first object keys with 
       current 
      [keys[1]]: obj[objKeys[1],  // object values
      [keys[2]]: obj[objKeys[3],
 });
}); 
console.log(newArray);

/* You also can change the key value asignation with a for, so you 
can handle not only 3 key values object, this could be optimized 
with es6 ans spread operator definition but rather to implement it in 
es5 for less complexity */

Upvotes: 0

Robby Cornelissen
Robby Cornelissen

Reputation: 97120

Using Object.entries() with some creative mapping, reducing, destructuring and spreading:

o = i.map(x => Object.entries(x).reduce((a, [k, v]) => ({...a, [i[0][k]]: v}), {}));

Complete snippet:

let input, output;

input = [
  {"A" : "Key1", "B" : "Key2", "C" : "Key3"},
  {"A" : "Data1", "B" : "Data2", "C" : "Data3"},
  {"A" : "Data5", "B" : "Data5", "C" : "Data7"}
];

output = input.map(x => Object.entries(x).reduce((a, [k, v]) => ({...a, [input[0][k]]: v}), {}));

console.log(output);

Upvotes: 0

dewfall
dewfall

Reputation: 41

let arr = [{"A" : "Key1", "B" : "Key2", "C" : "Key3"},
{"A" : "Data1", "B" : "Data2", "C" : "Data3"},
{"A" : "Data5", "B" : "Data5", "C" : "Data7"}];

const keys = Object.keys(arr[0]).map(i => arr[0][i]);
let result = arr.map(obj => {
    const replacedObj = {};
    const oriKeys = Object.keys(obj);
    for (let i = 0; i < keys.length; i++) {
        replacedObj[keys[i]] = obj[oriKeys[i]]
    };
    return replacedObj;
});
console.log(JSON.stringify(result));

Upvotes: 1

Related Questions