0

I would like to know how to get the array object based on values in javascript. I have array object obj1, obj2 , how to get the object if name of obj1 matches with obj2 values in javascript

var obj1=[
  {name: "country", value: "countries"},
  {name: "city", value: "cities"}
]
var obj2=[
  {countries:"countries"},
  {sample: "sample"}
]
var result = this.getMatchedObj(obj1, obj2);

function getMatchedObj(obj){
    const newlist = obj1.map((elem) => obj2.find(e=>Object.values(e)===elem.value));
    return newlist;
}

Expected Output:

[
 {name: "country", value: "countries"}
]

4 Answers 4

1

   var obj1=[
  {name: "country", value: "countries"},
  {name: "city", value: "cities"}
]
var obj2=[
  {countries:"countries"},
  {sample: "sample"}
]
let data = obj1.filter(ele=>obj2.findIndex(el=> Object.values(el)[0] ==ele.value)!=-1)
console.log(data);

 

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

Comments

0

If I understood you correctly, this should work:

var obj1=[
  {name: "country", value: "countries"},
  {name: "city", value: "cities"}
]
var obj2=[
  {countries:"countries"},
  {sample: "sample"}
]

function getMatchedObj(obj1, obj2){
    const values = obj2.reduce((acc, cur) => acc.concat(Object.values(cur)),[]);
    const newlist = obj1.filter(({value}) => values.includes(value));
    return newlist;
}
const result = getMatchedObj(obj1, obj2);
console.log(result);

Here's a playground:

https://stackblitz.com/edit/js-6tmjcc

Comments

0

You can can with this:

var obj1=[
  {name: "country", value: "countries"},
  {name: "city", value: "cities"}
];
var obj2=[
  {countries:"countries"},
  {sample: "sample"}
];

var item = obj1.find(item => obj2.map(x => Object.values(x)[0]).indexOf(item.value) > -1);

console.log(item);

Get all of the object property values from obj2 to an array. Then making an array to check existing with obj1


Or using for loop:

var obj1=[
  {name: "country", value: "countries"},
  {name: "city", value: "cities"}
];
var obj2=[
  {countries:"countries"},
  {sample: "sample"}
];

for (var obj of obj2) {
  var values = Object.values(obj);
  
  var item = obj1.find(item => values.indexOf(item.value) > -1);
  
  if (item) {
    console.log(item);
  }
}

Comments

0

Use filter, find and includes methods. If you just need one object, Then change filter call to find.

const getMatchedObj = (obj1, obj2) =>
  obj1.filter(({ value }) =>
    obj2.find((obj) => Object.values(obj).includes(value))
  );

var obj1 = [
  { name: "country", value: "countries" },
  { name: "city", value: "cities" },
];
var obj2 = [{ countries: "countries" }, { sample: "sample" }];

console.log(getMatchedObj(obj1, obj2));

Comments

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.