Find Array Key in Objects Array Given an Attribute Value

Find array key in objects array given an attribute value

Here is the functional approach:

$neededObjects = array_filter(
$objects,
function ($e) use ($idToFilter) {
return $e->id != $idToFilter;
}
);

Find a value in an array of objects in Javascript

You can loop over the array and test for that property:

function search(nameKey, myArray){
for (let i=0; i < myArray.length; i++) {
if (myArray[i].name === nameKey) {
return myArray[i];
}
}
}

const array = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];

const resultObject = search("string 1", array);
console.log(resultObject)

PHP - Find an object by key in an array of objects, update its value

By using array_column(), you can pull all the values with the index key in the arrays. Then you can find the first occurrence of the value a by using array_search(). This will only return the first index where it finds a value. Then you can simply replace that value, as you now have the index of that value.

$keys = array_column($objs, 'key');
$index = array_search('a', $keys);

if ($index !== false) {
$objs[$index]['value'] = 5;
}

See this live demo.

  • http://php.net/array_search
  • http://php.net/array_column

How to determine if Javascript array contains an object with an attribute that equals a given value?

2018 edit: This answer is from 2011, before browsers had widely supported array filtering methods and arrow functions. Have a look at CAFxX's answer.

There is no "magic" way to check for something in an array without a loop. Even if you use some function, the function itself will use a loop. What you can do is break out of the loop as soon as you find what you're looking for to minimize computational time.

var found = false;
for(var i = 0; i < vendors.length; i++) {
if (vendors[i].Name == 'Magenic') {
found = true;
break;
}
}

How to find index of an object by key and value in an javascript array

The Functional Approach

All the cool kids are doing functional programming (hello React users) these days so I thought I would give the functional solution. In my view it's actually a lot nicer than the imperatival for and each loops that have been proposed thus far and with ES6 syntax it is quite elegant.

Update

There's now a great way of doing this called findIndex which takes a function that return true/false based on whether the array element matches (as always, check for browser compatibility though).

var index = peoples.findIndex(function(person) {
return person.attr1 == "john"
});

With ES6 syntax you get to write this:

var index = peoples.findIndex(p => p.attr1 == "john");


The (Old) Functional Approach

TL;DR

If you're looking for index where peoples[index].attr1 == "john" use:

var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");

Explanation

Step 1

Use .map() to get an array of values given a particular key:

var values = object_array.map(function(o) { return o.your_key; });

The line above takes you from here:

var peoples = [
{ "attr1": "bob", "attr2": "pizza" },
{ "attr1": "john", "attr2": "sushi" },
{ "attr1": "larry", "attr2": "hummus" }
];

To here:

var values = [ "bob", "john", "larry" ];

Step 2

Now we just use .indexOf() to find the index of the key we want (which is, of course, also the index of the object we're looking for):

var index = values.indexOf(your_value);

Solution

We combine all of the above:

var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");

Or, if you prefer ES6 syntax:

var index = peoples.map((o) => o.attr1).indexOf("john");


Demo:

var peoples = [
{ "attr1": "bob", "attr2": "pizza" },
{ "attr1": "john", "attr2": "sushi" },
{ "attr1": "larry", "attr2": "hummus" }
];

var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");
console.log("index of 'john': " + index);

var index = peoples.map((o) => o.attr1).indexOf("larry");
console.log("index of 'larry': " + index);

var index = peoples.map(function(o) { return o.attr1; }).indexOf("fred");
console.log("index of 'fred': " + index);

var index = peoples.map((o) => o.attr2).indexOf("pizza");
console.log("index of 'pizza' in 'attr2': " + index);

How to get a key in a JavaScript object by its value?

function getKeyByValue(object, value) {
return Object.keys(object).find(key => object[key] === value);
}

ES6, no prototype mutations or external libraries.

Example,

function getKeyByValue(object, value) {  return Object.keys(object).find(key => object[key] === value);}

const map = {"first" : "1", "second" : "2"};console.log(getKeyByValue(map,"2"));

From an array of objects, extract value of a property as array

Here is a shorter way of achieving it:

let result = objArray.map(a => a.foo);

OR

let result = objArray.map(({ foo }) => foo)

You can also check Array.prototype.map().

How to find an object from array list

I'd suggest creating a requiredValues array, using Array.values() and Array.map().

This will look like:

[ "tv_40", "keyboard_40", "mouse_40" ]

We'd then use Array.filter() to find all stock items with every required value present in its attributes.

We'd use Array.every(), along with Array.find() to ensure every required value is present in the item attributes.

This would return a list of the stock items.

We can then map to get a list of matching stock ids:

const customerSelection = { "tv": [ { "value": "tv_40", "label": "Flat Screen" } ], "keyboard": [ { "value": "keyboard_40", "label": "Wireless Keyboard" } ], "mouse": [ { "value": "mouse_40", "label": "Wireless Mouse" } ] };

const availableStock = [ { "stockId": "elec_c1_f1", "attributes": [ { "label": "Flat Screen", "value": "tv_41" }, { "label": "Wireless Keyboard", "value": "keyboard_41" }, { "label": "Wireless Mouse", "value": "mouse_41" } ] }, { "stockId": "elec_c1_f2", "attributes": [ { "label": "Flat Screen", "value": "tv_40" }, { "label": "Wireless Keyboard", "value": "keyboard_40" }, { "label": "Wireless Mouse", "value": "mouse_40" } ] }, { "stockId": "elec_c1_f3", "attributes": [ { "label": "Flat Screen", "value": "tv_42" }, { "label": "Wireless Keyboard", "value": "keyboard_42" }, { "label": "Wireless Mouse", "value": "mouse_42" } ] } ]

// These values must be present in the attributes...
const requiredValues = Object.values(customerSelection).map(val => val[0].value);

// Use Array.filter() to find stock items that match _all_ required attributes...
const foundItems = availableStock.filter(item => {
return requiredValues.every(value => item.attributes.find(attr => attr.value === value));
});

console.log('Found stockIds:', foundItems.map(({ stockId }) => stockId));
console.log('Found items:', foundItems);
.as-console-wrapper { max-height: 100% !important; top: 0; }


Related Topics



Leave a reply



Submit