0

Currently I am using array of object which is "mainArr" mentioned bellow ,

I am trying to filter objects property by a loop inside a function which looks like bellow , but based on the param passed, I want obj.name (object property) to be replaced by obj."param". I need both values of name and nametwo values in different functionality hence I have created a function, I tried replacing it with string variable but its not working.

let mainArr = [{
    name: "ram",
    age: 30,
    nametwo: "shiva"
  },
  {
    name: "geetha",
    age: 20,
    nametwo: "anjali"
  }
];

let compareArr = ["ram"];

const test = (param) => {
  let finalArr = [];
  mainArr.filter((obj) => {
    return compareArr.includes(obj.name); //how to replace .name with param?
  });
}


test("nametwo");
Divakar R
  • 773
  • 1
  • 8
  • 36

1 Answers1

1

You can use obj[key] to do it(key is an variable)

let mainArr = [{
    name: "ram",
    age: 30,
    nametwo: "shiva"
  },
  {
    name: "geetha",
    age: 20,
    nametwo: "anjali"
  }
]

let compareArr = ["ram"];

const test = (param) => {
  let finalArr = [];
  let key ='name';// you can assign value of key dynamiclly
  mainArr.forEach(obj=>{
    console.log(obj[key]);
 });
}


test("nametwo");
flyingfox
  • 13,414
  • 3
  • 24
  • 39