0

I have two array of object I want to compare one object value with other object key and push result to third array. please help...

arr1 = [
{head: "first_name", value:"First Name"}, 
{head: "last_name", value:"Last Name"}, 
{head: "age", value:"Age"}];

arr2 = [
{car:"aa", xyz:"asdsa", abc:"dsds",first_name: "Jack", last_name: "Dan", age:"25"},
{car:"bb", xyz:"asdsa", abc:"dsds",first_name: "Mark", last_name: "Wood", age:"28"},
{car:"cc", xyz:"asdsa", abc:"dsds",first_name: "Carl", last_name: "R", age:"25"},
{ car:"dd", xyz:"asdsa", abc:"dsds",first_name: "Max", last_name: "P", age:"25"}
]

arr1.map(el=> {
arr2.map(elm => {
if(el.head === elm.object.key){
arr3.push(elm)
}
})
})

Expected output:
arr3 = arr2 = [
{first_name: "Jack", last_name: "Dan", age:"25"},
{first_name: "Mark", last_name: "Wood", age:"28"},
{first_name: "Carl", last_name: "R", age:"25"},
{first_name: "Max", last_name: "P", age:"25"}
]
Vishnu Shenoy
  • 862
  • 5
  • 18
  • 1. Don't use `map` when you're writing `forEach` code. 2. There is no `elm.object` 3. you have to map over `arr2`, using `Object.values(arr1)` to compose the new object (you're simply pushing to a new array, but the objects you want don't exist yet) –  Jul 30 '20 at 10:46

1 Answers1

1

Here is the logic in an immutable way. Tested and works fine.

const arr3 = arr2.map((item) => {
  const keys = arr1.map((keyObject) => keyObject.head);
  return keys.reduce((mem, key) => {
    mem[key] = item[key];
    return mem
  }, {})
})

Here is the snapshot of the output executed in the console.

Snapshot of output

Vasanth Gopal
  • 1,215
  • 10
  • 11
  • May I know as to why it's voted down?. It produces the exact expected result. – Vasanth Gopal Jul 30 '20 at 10:52
  • the resulting output has all the key value pair as in arr2, I want only 3 key value pair that too in same order. Can u please chk the expected output – Vishnu Shenoy Jul 30 '20 at 10:57
  • @VishnuShenoy - I have attached a snapshot of the output I got by running the above code. It seem to have only the expected keys and not all the keys. Are you sure the code did not produce the expected result? – Vasanth Gopal Jul 30 '20 at 11:03
  • i have given one up, the resulting value is in arr3 right – Vishnu Shenoy Jul 30 '20 at 11:05
  • I have edited and added `const arr3 = ` to the result. Now the result will be in `arr3`. Hope am right. Kindly let me know. – Vasanth Gopal Jul 30 '20 at 11:07
  • The answer to order the keys is available here - https://stackoverflow.com/questions/5467129/sort-javascript-object-by-key – Vasanth Gopal Jul 30 '20 at 11:09
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/218887/discussion-between-vasanth-gopal-and-vishnu-shenoy). – Vasanth Gopal Jul 30 '20 at 11:20