Beginner
Beginner

Reputation: 9095

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

Upvotes: 1

Views: 58

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386520

You could replace existent key of object and rebuild new objects.

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

Upvotes: 1

Related Questions