1

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


4
  • please add what does not work. Commented Jun 4, 2019 at 6:10
  • What have you tried so far? Please show us that as well Commented Jun 4, 2019 at 6:11
  • What if there are multiple objects whereby the arr contains 7 as well? Commented Jun 4, 2019 at 6:12
  • Just for a demo, values inside array are unique Commented Jun 4, 2019 at 6:13

3 Answers 3

2

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))

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

Comments

1

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

3 Comments

The code will throw error if no arr of any object will not contain the given key.
@MaheerAli thanks for the reminder. In that case, [0].val should be on a separate statement, and should only run if the array isn't empty?
You can either store the result of filter()[0] in a variable and then use ternary operator to return a value. Or either use || {}. Like (data.filter(obj => obj.arr.includes(7))[0] || {}).val
0

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

1 Comment

for (i of x) here you are declaring a global variable. Use let before i. And also answers like try this are not encouraged you should explain what you are doing in code.

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.