1

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

6
  • what does not work? Commented May 27, 2019 at 15:16
  • i didnt undestand Commented May 27, 2019 at 15:17
  • He mean that what have you tried so far and where have you struck? Commented May 27, 2019 at 15:17
  • {Test 1: "1", Test 2: "2", Test 3: null ,default:"123134" } Is not a valid object Commented May 27, 2019 at 15:19
  • updated the key Commented May 27, 2019 at 15:22

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

i need to get all the keys, the expected array of each object consist of every key. Can you check the expectedData in the question
i am trying update the structure in a different way, can you help me on this stackoverflow.com/questions/56339879/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.