Using PHP I can return the key by looking up the value inside an array.
<?php
$array = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple');
while ($fruit_name = current($array)) {
if ($fruit_name == 'apple') {
echo key($array).'<br />';
}
next($array);
}
?>
But I'm learning javascript, I've searched and haven't found a solution, I'm still a beginner.
How can I return the key by fetching the value within a given array?
I've already tried using its functions: .indexOf() or .findIndex()
var array = [];
array['key'] = 'Value';
array['car'] = 'Ferrari';
array['car2'] = 'BMW';
console.log(key='Ferrari'??);
How to Return 'car' if Value = 'Ferrari' ?
another doubt in this case is it better to use Array or Class? Is it possible to return the class key?
var pessoas = {'car': 'Ferrari', 'car2':'BMW'};
Arrays don't have keys, only numeric indexes. When you pass a string to an Array, you are actually creating a new property for the Array object, not a new item in the Array data (for example, .length is a property of an Array, not an indexed value).
var array = [];
// The following 3 lines don't create indexed values in the array:
array['key'] = 'Value';
array['car'] = 'Ferrari';
array['car2'] = 'BMW';
// Which is proven here:
console.log(array.length); // 0
// What they do is create new properties on the Array instance:
console.log(array.car2); // "BMW"
If you need keys, use an object, which is structured as follows:
{key: keyValue, key: keyValue, key:keyValue ...}
where the key is always a string, so quotes around the key name are not necessary.
var pessoas = {car: 'Ferrari', car2:'BMW'};
console.log("The second car is: " + pessoas.car2);
console.log("The keys and key names are: ");
for (var prop in pessoas){
console.log(prop + " : " + pessoas[prop]);
}
You should use Objects instead of arrays in JavaScript to store PHP equivalent of arrays with keys. In JS if you make an array, add non numeric keys to it and then do .length it will give 0. So many built in functions do not work, like .filter .find and .map.
//your way
let pessoas = [];
pessoas ["car1"] = "Ferrari";
pessoas ["car2"] = "BMW";
//the safe way. Both ways work.
pessoas = {'car': 'Ferrari', 'car2':'BMW'};
function getObjKey(obj, value) {
return Object.keys(obj).find(key => obj[key] === value);
}
console.log(getObjKey(pessoas, 'BMW'));
Additionally, you can turn string-keyed arrays into object like this:
function getObjKey(obj, value) {
return Object.keys(obj).find(key=>obj[key] === value);
}
var arrayToObject = (array)=>Object.keys(array).reduce((acc,curr)=>(acc[curr] = array[curr],
acc), {});
let pessoas = [];
pessoas["car1"] = "Ferrari";
pessoas["car2"] = "BMW";
pessoas.push("corretArray");
pessoas = arrayToObject(pessoas);
console.log(getObjKey(pessoas, 'BMW'));
Related
so I want to find unique values from an array.
so for example I have this array:
const mainArr = ['shape-10983', 'size-2364', 'size-7800', 'size-4602', 'shape-11073', 'size-15027', 'size-15030', 'size-15033', 'height-3399', 'height-5884']
so I want to find the first matching value for each unique item.
for example, in the array, I have two strings with the shape prefix, six items with the size prefix, and two items with the height prefix.
so I want to output to be something like
const requiredVal = ["shape-10983", "size-2364", "height-3399"]
I want only the first value from any set of different values.
the simplest solution will be to iterate on the list and storing what you got in a dictionary
function removeSimilars(input) {
let values = {};
for (let value of input) {//iterate on the array
let key = value.splitOnLast('-')[0];//get the prefix
if (!(key in values))//if we haven't encounter the prefix yet
values[key] = value;//store that the first encounter with the prefix is with 'value'
}
return Object.values(values);//return all the values of the map 'values'
}
a shorter version will be this:
function removeSimilars(input) {
let values = {};
for (let value of input)
values[value.splitOnLast('-')[0]] ??= value;
return Object.values(values);
}
You could split the string and get the type and use it aks key for an object along with the original string as value. At result take only the values from the object.
const
data = ['shape-10983', 'size-2364', 'size-7800', 'size-4602', 'shape-11073', 'size-15027', 'size-15030', 'size-15033', 'height-3399', 'height-5884'],
result = Object.values(data.reduce((r, s) => {
const [type] = s.split('-', 1);
r[type] ??= s;
return r;
}, {}));
console.log(result);
If, as you mentioned in the comments, you have the list of prefixes already available, then all you have to do is iterate over those, to find each first element that starts with that prefix in your full list of possible values:
const prefixes = ['shape', 'size', 'height'];
const list = ['shape-10983', 'size-2364', 'size-7800', 'size-4602', 'shape-11073', 'size-15027', 'size-15030', 'size-15033', 'height-3399', 'height-5884']
function reduceTheOptions(list = [], prefixes = [], uniques = []) {
prefixes.forEach(prefix =>
uniques.push(
list.find(e => e.startsWith(prefix))
)
);
return uniques;
}
console.log(reduceTheOptions(list, prefixes));
Try this:
function getRandomSet(arr, ...prefix)
{
// the final values are load into the array result variable
result = [];
const randomItem = (array) => array[Math.floor(Math.random() * array.length)];
prefix.forEach((pre) => {
result.push(randomItem(arr.filter((par) => String(par).startsWith(pre))));
});
return result;
}
const mainArr = ['shape-10983', 'size-2364', 'size-7800', 'size-4602', 'shape-11073', 'size-15027', 'size-15030', 'size-15033', 'height-3399', 'height-5884'];
console.log("Random values: ", getRandomSet(mainArr, "shape", "size", "height"));
I modified the #ofek 's answer a bit. cuz for some reason the ??= is not working in react project.
function removeSimilars(input) {
let values = {};
for (let value of input)
if (!values[value.split("-")[0]]) {
values[value.split("-")[0]] = value;
}
return Object.values(values);
}
create a new array and loop over the first array and check the existing of element before in each iteration if not push it to the new array
Here I want to read key name of obj.
Like "CIRTGroupBox1", "CIRTGroupBox2"
Try this :
var arr = [{
'CIRTGroupBox1': ''
}, {
'CIRTGroupBox2': ''
}, {
'CIRTGroupBox3': ''
}];
// Using array.map() method
var usingMapKeys = arr.map((obj) => Object.keys(obj)[0]);
// Using Object.entries() method
var usingEnteriesKeys = arr.map((obj) => Object.entries(obj)[0][0]);
console.log(usingMapKeys);
console.log(usingEnteriesKeys);
is it?
var x = {
"ob1": "value",
"ob2": {
"ob21": "value"
}
};
var keys = Object.keys(x);
console.log(keys);
You can do that using Object.keys method in JS like below
var keys = Object.keys(groupBoxesTemp);
This will return string array and each item in it is the key of this object.
If you want to read values pertaining those 2 keys, you can do like below using the for-in loop:
for(item in groupBoxesTemp){
console.log('key is: ', item);
console.log('value is: ', groupBoxesTemp[item]);
}
Based on your screenshot, temp is an array of objects which has 3 objects in it. You can do that too like below:
temp.forEach(function(item, index){
//key for all objects in the array will be logged.
console.log( Object.keys(item) );
});
I have an array of similarly structured objects:
var my_arr = [{property1: some_value, property2: another_value}, {}, {}, ...];
Currently, to find the object containing a target value, I iterate through each element of the array:
var my_obj, target_value;
for (let obj_in_arr of my_arr) {
if (obj_in_arr.property1 === target_value) {
my_obj = obj_in_arr;
break;
}
}
Is there a faster way? How can I access the object with the target value directly, without resorting to iteration?
If you prepopulate a new Map all subsequent searches will be in O(1)
const objMap = new Map()
for (let obj of my_arr) {
objMap.set(obj.property1, obj)
}
function getObject(target, map) {
return map.get(target)
}
I think you need to iterate the array anyway, but you can try _.findIndex of underscore.js
http://underscorejs.org/#findIndex
If you only need to find a value once, then iteration is really the only way.
If you will want to find many values in the array, you could create an object keyed on your target property to serve as a lookup table:
var lookup = {};
for (var i = 0; i < my_arr.length; i++) {
lookup[my_arr[i].property1] = my_arr[i];
}
That front loads some work, but could save you time ultimately if you have many lookups to make.
Lookups would be as simple as:
my_obj = lookup[target_value];
If you have access to es2015 you could make your lookup table generation a little more concise:
const lookup = my_arr.reduce((m, v) => (m[v.property1] = v, m), {});
this will still iterate through the array but you could use the native js find function.
const objArray = [{ val: 1}, { val: 2}];
const targetObj = objArray.find((obj) => obj.val == 2 ) // { val: 2}
I have an array like this:
var myArray = new Array();
myArray['foo'] = {
Obj: {
key: value
}
};
myArray['bar'] = {
Obj: {
key: value
}
};
When I do console.log(myArray) I just get empty [ ]. And when I try to iterate the array using jQuery's each the function doesn't run.
How can I get the 'foo' and 'bar' parts of the array?
Example code:
console.log(myArray); // [ ]
jQuery.each(myArray, function(key, obj) {
console.log(key); // should be 'foo' following by 'bar'
});
In addition, why does this work:
jQuery.each(myArray[foo], function(obj, values) {
// Why does this work if there are no associative arrays in JS?
});
you can get keys by:
Object.keys(variable name);
it returns array of keys.
You need to define it as an object if you want to access it like that:
var myObj= {};
myObj.foo = ...;
myObj.bar = ...;
Now you can access the properties like myObj["bar"] or myObj.bar
Note:
To loop through all the properties it's wise to add an additional check. This is to prevent you from looping through inherited properties.
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
// Do stuff.
}
}
Array is a collection where each element has an index.
To add element to array you can use push method
myArray.push('someValue');
or set element by index (if length of array < index):
myArray.push('someValue1');
myArray.push('someValue1');
myArray[0] = 'new someValue1';
Note that array is an instance of Object class, so you can add/edit any property of this object:
myArray.foo = '1';
myArray['bar'] = '2';
In this case you will not add new element to array, you defining new properties of object.
And you don't need to create object as Array if you don't wont to use indexes.
To create new object use this code:
var myObj = {};
To get all properties of object see
How to get all properties values of a Javascript Object (without knowing the keys)?
var myArray = {};
myArray['foo'] = { 'key': 'value' }
myArray['bar'] ={ 'key': 'value' }
console.log(myArray)
jQuery.each(myArray['foo'], function(obj, values) {
console.log(obj, values)
});
Demo
With your Array of Objects you could use this function:
var getKeys = function(obj) {
if (!(typeof obj == "object")) return [];
var keys = [];
for (var key in obj) if (obj != null && hasOwnProperty.call(obj, key)) keys.push(key);
return keys;
};
getKeys(myArray) would give you an array of your Keys.
This is basically a cleared up version of underscores _.keys(myArray) function. You should consider using underscore.
// $.each() function can be used to iterate over any collection, whether it is an object or an array.
var myArray = {};
myArray['alfa'] = 0;
myArray['beta'] = 1;
$.each(myArray, function(key, value) {
alert(key);
});
Note: checkout http://api.jquery.com/jQuery.each/ for more information.
if you are looking for Get/Delete/Sum/IsExist functions for an array of objects using javascript, I have posted this question and answer for such functions
Remove Object from an Array using JavaScript
Is Exist for an Object from an Array using JavaScript
Select Object from an Array using JavaScript
Sum Object values in an Array using JavaScript
How do I check if an array includes an object in JavaScript?
How do I remove a particular element from an array in JavaScript?
Find object by id in an array of JavaScript objects
summing numbers stored in an array in JavaScript, sum values of a javascript array?, Loop through array and return sum of all values
Btw, your question doesn't have much to do with JSON, and naught with jQuery.
Just use underscore.
Remove from a simple array:
var newList = _.without(list, 'hello', 'world'); // Remove any instance of 'hello' and 'world'
Remove from an array of objects:
var toRemove = _.where(list, {title: 'hello', subtitle: 'world'});
var newList = _.difference(list, toRemove);
Exists in array:
var exists = _.contains(list, value);
Get item from array:
var item = _.find(list, function(i){ i === value }); // For simple types
var item = _.findWhere(list, {title: 'hello', subtitle: 'world'}); // For complex types
Sum items:
var sum = _.reduce(list, function(start, num){ return start + num; }, 0);
And A LOT more.
4 Javascript Helpers
Remove Object from an Array using JavaScript
Is Exist for an Object from an Array using JavaScript
Select Object from an Array using JavaScript
Sum Object values in an Array using JavaScript
var JShelpers = {
removeItemFromArray: function (myObjects, prop, valu) {
return myObjects.filter(function (item) {
return item[prop] !== valu;
});
},
isExistInArray: function (myObjects, prop, valu) {
var i = myObjects.length;
while (i--) {
if (myObjects[i][prop] == valu) {
return true;
}
}
return false;
},
getItemFromArray: function (myObjects, prop, valu) {
var i = myObjects.length;
while (i--) {
if (myObjects[i][prop] == valu) {
return myObjects[i];
}
}
return "";
},
sumItemInArray: function (myObjects, prop) {
var summation = 0;
myObjects.forEach(function (item) {
summation += parseFloat(item[prop]);
});
return summation;
}
}
Example:
Say you have an array of Employees in a Json Format like this
var employeesArray = [{"Id":1,"Name":"tom","Age":15},{"Id":2,"Name":"Harry","Age":17}];
And you want to retrieve employee by his Age not only ID (as common) ,
you can simply call
JShelpers.getItemFromArray(employeesArray,"Age",15)