joy08
joy08

Reputation: 9652

Need to fetch a property based on iteration over an array with respect to array of objects

I have an array of objects with the following format. Each object has got few properties and also an array. I have to fetch a property if a key is present in the array.

Consider the below object: When I give key as 7 it should return me 'xyz'. If key is 3 it should give me 'abc'

[
  {
    val : 'abc',
    arr : [1,2,3,4]
  },

  {
    val: 'xyz',
    arr : [7,8,9]
  }
]


Upvotes: 1

Views: 42

Answers (3)

Maheer Ali
Maheer Ali

Reputation: 36564

You can use find() and includes(). Use find of the main array and check if the arr of that object includes() the given key. return the val property of the found object.

const arr = [
  {
    val : 'abc',
    arr : [1,2,3,4]
  },

  {
    val: 'xyz',
    arr : [7,8,9]
  }
]

const getVal = (arr,key) => (arr.find(x => x.arr.includes(key)) || {}).val;

console.log(getVal(arr,3))
console.log(getVal(arr,7))

Upvotes: 2

mehta-rohan
mehta-rohan

Reputation: 1341

You can try this too.

var x = [{
        val: 'abc',
        arr: [1, 2, 3, 4]
    },

    {
        val: 'xyz',
        arr: [7, 8, 9]
    }
];
var test = function(data, key) {
    for (let i of x) {
        if (i.arr.indexOf(key) >= 0)
            return i.val;
    }
}

// example

console.log(test(x,9));

Upvotes: 0

wentjun
wentjun

Reputation: 42516

You can use Array.filter() to filter the object which meets the condition whereby the element (7) exists in the array. Within the callback function for Array.some(), you can use Array.includes() to check if the element (7), exists in the arr property itself:

const data = [
  {
    val : 'abc',
    arr : [1,2,3,4]
  },

  {
    val: 'xyz',
    arr : [7,8,9]
  }
]

const res = data.filter(obj => obj.arr.includes(7))[0].val;
console.log(res);

Upvotes: 1

Related Questions