首页 > 解决方案 > replacing the key value with another property in array of objects

问题描述

merging array with object and returning an array with all the properties with array of object value or null

let object = {
  keys: {
    test1: {label: "Test_1"},
    test2: {label: "Test_2"},
    test3: {label: "Test_3"}
  }
}

let data = [{test1: "1", test2: "2", default:"123134" }, {test1: "1", test2: "2", default:"123134"}, {test1: "1", test3: "3"}, {test3: "3"}]

I am expecting the below array of objects

let expectedArray = [{Test_1: "1", Test_2: "2", Test_3: null ,default:"123134" }, {Test_1: "1", Test_2: "2", Test_3: null,  default:"123134"}, {Test_1: "1", Test_3: "3", Test_2:null }, {Test_3: "3", Test_1: null, Test_2: null}]

Tried below snippet

let res = data.map(o => {
  let obj = {}
  let c = Object.keys(o).forEach(aa => {
      obj[object.keys[aa].label] = o[aa]
  })
  return obj
})

Any help appreciated

标签: javascript

解决方案


您可以替换对象的现有键并重建新对象。

var object = { keys: { test1: { label: "Test 1" }, test2: { label: "Test 2" }, test3: { label: "Test 3" } } },
    data = [{ test1: "1", test2: "2", default: "123134" }, { test1: "1", test2: "2", default: "123134" }, { test1: "1", test3: "3" }, { test3: "3" }],
    templates = Object.values(object.keys).map(({ label }) => ({ [label]: null })),
    result = data.map(o => Object.assign(
        {},
        ...templates,
        ...Object
            .entries(o)
            .map(([k, v]) => ({ [k in object.keys ? object.keys[k].label : k]: v }))
    ));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


推荐阅读