对象“键”要分配另一个对象“值”

时间:2019-05-30 10:00:49

标签: javascript arrays object

var tableHeader = [{
    header: "Name",
    field: "name" // this value assign to key in tbl_obj (below is there)

  },
  {
    header: "Degree",
    field: "degree"
  },
  {
    header: "Age",
    field: "age"
  },
];
var tbl_obj = [{
    name: "John",
    degree: "CSE",
    age: "25"
  },
  {
    name: "Hussain",
    degree: "EEE",
    age: "23"
  },
  {
    name: "Ganesh",
    degree: "ECE",
    age: "22"
  }
]

1 个答案:

答案 0 :(得分:0)

您可以使用mapfindObject.entriesreduce来做到这一点。请注意,由于所有对象中的所有键都位于替换数组中,因此所有值都将被替换。

var tableHeader = [{header:"Name",field:"name"},{header:"Degree",field:"degree"},{header:"Age",field:"age"}];
var tbl_obj = [{name:"John",degree:"CSE",age:"25"},{name:"Hussain",degree:"EEE",age:"23"},{name:"Ganesh",degree:"ECE",age:"22"}];
const res = tbl_obj.map(e => Object.entries(e).reduce((acc, [k, v]) => {
  let found = tableHeader.find(({ field }) => field == k);
  if (found) acc[k] = found.header;
  else acc[k] = v;
  return acc;
}, {}));
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }