Getting a list of associative array keys
You can use: Object.keys(obj)
Example:
var dictionary = {
"cats": [1, 2, 37, 38, 40, 32, 33, 35, 39, 36],
"dogs": [4, 5, 6, 3, 2]
};
// Get the keys
var keys = Object.keys(dictionary);
console.log(keys);
Getting keys of an associative array in JavaScript
You can try with flatMap()
The
flatMap()
method first maps each element using a mapping function, then flattens the result into a new array. It is identical to amap()
followed by aflat()
of depth 1, butflatMap()
is often quite useful, as merging both into one method is slightly more efficient.
and Object.keys()
The
Object.keys()
method returns an array of a given object's own enumerable property names, in the same order as we get with a normal loop.
var assocArray = [{a : "" },{b : ""},{c : ""}]; var keys = assocArray.flatMap(i => Object.keys(i));console.log(keys);
Can I get all keys of an multi level associative arrays in php
Dereleased's solution will be faster I guess (as it uses internal loops), mine can also deal with array values for object_id
keys. Your tradeoff ;)
function find_all($needle, array $haystack, array &$result = null) {
// This is to initialize the result array and is only needed for
// the first call of this function
if(is_null($result)) {
$result = array();
}
foreach($haystack as $key => $value) {
// Check whether the key is the value we are looking for. If the value
// is not an array, add it to the result array.
if($key === $needle && !is_array($value)) {
$result[] = $value;
}
if(is_array($value)) {
// If the current value is an array, we perform the same
// operation with this 'subarray'.
find_all($needle, $value, $result);
}
}
// This is only needed in the first function call to retrieve the results
return $result;
}
As you can see, the result array is given to every call of the function as reference (denoted by the &
). This way, every recursive call of this function has access to the same array and can just add a find.
You can do:
$values = find_all('object_id', $array);
It gives me for your array:
Array
(
[0] => 12061
[1] => 100012061
[2] => 1000000000015
[3] => 10001
[4] => 12862
[5] => 12876
[6] => 1206102000
[7] => 1206104000
[8] => 1206101000
[9] => 1206105000
[10] => 1206106000
[11] => 10017
[12] => 100010017
[13] => 300306
[14] => 12894
[15] => 12862
[16] => 12876
[17] => 1001701000
[18] => 11990
[19] => 100011990
[20] => 12862
[21] => 12876
[22] => 10017
[23] => 12894
)
How can I get the list of indices an associative array has?
I have an associative array in
awk
, and I can iterate over the
values of the array using (e.g.) for(v in ARRAY) ...
.
As far I as know it will do iterate over keys, consider following example
awk 'BEGIN{arr["a"]=1;arr["b"]=2;arr["c"]=3}END{for(i in arr){print i}}'
output
a
b
c
(tested in gawk 4.2.1)
PHP Get values from associative array based on list of matched keys
You should use this.
foreach($post_data as $key=>$value){
if(in_array($key,$my_fields)){
$clean_data[$key]=$value;
}
}
print_r($clean_data);
You are trying in the right direction, just the matching of key in the array has to be in a different way.
How to get first n keys in associative array in PHP?
Sort the array in reverse order keeping association with arsort(). Then take a slice of the array (first three elements).
arsort( $scores );
$topScores = array_slice( $scores, 0, 3 );
You can then use implode to generate a string from the sliced array.
Rizier123 pointed out you wanted the keys in the string, so you'd need to implode the keys. Something like
$topScoresStr = implode( ', ', array_keys( $topScores ) );
Associative arrays - grabbing specific keys and values
Just Change your foreach
loop
This:
<?php
$items = [
'Mac' => [
'quantity' => $qty1,
'price' => 1899.99
],
'Razer Mouse' => [
'quantity' => $qty2,
'price' => 79.99
],
'WD HDD' => [
'quantity' => $qty3,
'price' => 179.99
],
'Nexus' => [
'quantity' => $qty4,
'price' => 249.99
],
'Drums' => [
'quantity' => $qty5,
'price' => 119.99
]
];
foreach($items as $key => $arrVal) {
if($key == 'Mac')
echo $key ."=". $arrVal['quantity'];
}
?>
The if(){}
controls which key
is getting printed so if you want to printNexus
just change the value from Mac
to Nexus
or smthing and if you want to check multiple ones just use ||
like this if($key == 'Mac' || $key == 'Nexus')
||
= OR
And if you want to get price just change $arrVal['quantity'];
to $arrVal['price'];
Javascript :: How to get keys of associative array to array variable?
Is there any easy/short way how to get array of keys to array variable without loop..?
Yes, ECMAScript 5 defines Object.keys
to do this. (Also Object.getOwnPropertyNames
to get even the non-enumerable ones.) Most moderns browser engines will probably have it, older ones won't, but it's easily shimmed (for instance, this shim does).
If so, additionally, is possible to apply some regular expression to key list to get just keys that match such pattern (let's say
/^x/
) without (another) loop?
No, no built-in functionality for that, but it's a fairly straightforward function to write:
function getKeys(obj, filter) {
var name,
result = [];
for (name in obj) {
if ((!filter || filter.test(name)) && obj.hasOwnProperty(name)) {
result[result.length] = name;
}
}
return result;
}
Or building on Object.keys
(and using ES2015+ features, because I'm writing this part in late 2020):
function getKeys(obj, filter) {
const keys = Object.keys(obj);
return !filter ? keys : keys.filter(key => filter.test(key) && obj.hasOwnProperty(key));
}
php: how to get associative array key from numeric index?
You don't. Your array doesn't have a key [1]
. You could:
Make a new array, which contains the keys:
$newArray = array_keys($array);
echo $newArray[0];But the value "one" is at
$newArray[0]
, not[1]
.
A shortcut would be:echo current(array_keys($array));
Get the first key of the array:
reset($array);
echo key($array);Get the key corresponding to the value "value":
echo array_search('value', $array);
This all depends on what it is exactly you want to do. The fact is, [1]
doesn't correspond to "one" any which way you turn it.
Related Topics
Clearing Localstorage in JavaScript
How to Make a Div Element Editable (Like a Textarea When I Click It)
Understanding React-Redux and Mapstatetoprops()
Does Execcommand Saveas Work in Firefox
Remove Characters from a String
How Not to Forget Using Await Everywhere in JavaScript
How to Serialize an Input File Object to JSON
Chaining .Bind() Calls in JavaScript. Unexpected Result
Create an Empty Object in JavaScript with {} or New Object()
Skip Arguments in a JavaScript Function
Pass JavaScript Variable to Flask Url_For
Thickness of Lines Using Three.Linebasicmaterial
Should I Refrain from Handling Promise Rejection Asynchronously
Jslint Is Suddenly Reporting: Use the Function Form of "Use Strict"
How Do the JavaScript Relational Comparison Operators Coerce Types
JavaScript 'In' Operator for 'Undefined' Elements in Arrays