根据对象数组中的第一个“行”重命名JSON键

时间:2018-12-12 02:01:44

标签: javascript node.js json

我有一个JSON对象数组,我需要根据第一个对象中的值重命名键。尝试在NodeJS中执行此操作,但没有任何运气。

我可能会通过几个循环来强行使用它,但是由于“列”的数量会不时变化,因此我希望有一个更具可扩展性的解决方案。

这是一个例子

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

我希望结果像

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

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

Object.entries()与一些广告素材mappingreducingdestructuringspreading结合使用:

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

完整代码段:

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

答案 2 :(得分:0)

让我们说旧数组存储在一个名为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 */