Find Name of Array obj from Json - javascript

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

Related

Return the key from a JavaScript array?

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

How can I convert an array of objects to a basic object? [duplicate]

I want to convert an array of objects to object with key value pairs in javascript.
var arr=[{"name1":"value1"},{"name2":"value2"},...}];
How can i convert it to an object such as
{"name1":"value1","name2":"value2",...}
I want it to be supported in majority of browsers.
You could use Object.assign and a spread syntax ... for creating a single object with the given array with objects.
var array = [{ name1: "value1" }, { name2: "value2" }],
object = Object.assign({}, ...array);
console.log(object);
You could run a reduce over the array and return a new object. But it is important to remember that if properties are the same they will be overwritten.
const newObject = array.reduce((current, next) => {
return { ...current, ...next};
}, {})
If you are using es5 and not es6:
var newObject = array.reduce(function(current, next){
return Object.assign({}, current, next);
}, {})
With modern JS (YMMV):
Split each object into entries
Aggregate all entries into one object
const arr = [{name1:"value1"}, {name2:"value2"}, {a:1,b:2}];
const obj = Object.fromEntries(arr.flatMap(Object.entries));
console.log(obj);
Try this simple logic
var arr=[{"name1":"value1"},{"name2":"value2"}];
var obj = {}; //create the empty output object
arr.forEach( function(item){
var key = Object.keys(item)[0]; //take the first key from every object in the array
obj[ key ] = item [ key ]; //assign the key and value to output obj
});
console.log( obj );
use with Array#forEach and Object.keys
var arr = [{"name1": "value1"},{"name2": "value2"}];
var obj = {};
arr.map(k => Object.keys(k).forEach(a => obj[a] = k[a]))
console.log(obj)
Using for...in loop :
var arr=[{"name1":"value1"},{"name2":"value2"}];
var obj = {};
for (var i in arr) {
obj[Object.keys(arr[i])] = arr[i][Object.keys(arr[i])];
}
console.log(obj);
Using Array.map() method with ES6 :
var arr=[{"name1":"value1"},{"name2":"value2"}];
var obj = {};
arr.map(item => obj[Object.keys(item)] = item[Object.keys(item)]);
console.log(obj);
Using Object.assign() method with ES6 spreaqd(...) assignment :
let arr=[{"name1":"value1"},{"name2":"value2"}];
let obj = Object.assign({}, ...arr);
console.log(obj);

JavaScript - Filter <key,value> Object by key

I am looking for a short and efficient way to filter objects by key, I have this kind of data-structure:
{"Key1":[obj1,obj2,obj3], "Key2":[obj4,obj5,obj6]}
Now I want to filter by keys, for example by "Key1":
{"Key1":[obj1,obj2,obj3]}
var object = {"Key1":[1,2,3], "Key2":[4,5,6]};
var key1 = object["Key1"];
console.log(key1);
you can use the .filter js function for filter values inside an object
var keys = {"Key1":[obj1,obj2,obj3], "Key2":[obj4,obj5,obj6]};
var objectToFind;
var keyToSearch = keys.filter(function(objects) {
return objects === objectToFind
});
The keyToSearch is an array with all the objects filter by the objectToFind variable.
Remember, in the line return objects === objectToFind is where you have to should your statement. I hope it can help you.
You can create a new object based on some custom filter criteria by using a combination of Object.keys and the array .reduce method. Note this only works in es6:
var myObject = {"Key1":["a","b","c"], "Key2":["e","f","g"]}
function filterObjectByKey(obj, filterFunc) {
return Object.keys(obj).reduce((newObj, key) => {
if (filterFunc(key)) {
newObj[key] = obj[key];
}
return newObj;
}, {});
}
const filteredObj = filterObjectByKey(myObject, x => x === "Key1")
console.log(filteredObj)
Not sure what exactly are you trying to achieve, but if you want to have a set of keys that you would like to get the data for, you have quite a few options, one is:
var keys = ['alpha', 'bravo'];
var objectToFilterOn = {
alpha: 'a',
bravo: 'b',
charlie: 'c'
};
keys.forEach(function(key) {
console.log(objectToFilterOn[key]);
});

Underscore: How to return all values by array with keys

I have big object with a lot of key : value, and I have array with some keys from this object.
How to return values of this keys(array) by underscore?
I try some like this, but it's bull**
_.find(objectwithkeysandvalues , function(value){
return _.intersection(value,arraywithekeys)
});
You don't need Underscore for this task. Instead, you can use the map function to create a new array that contains the values specified by the keys in the old array:
var myValues = keys.map(function (key) {
return myObject[key]
});
You only need to map each value from your keys array to yourBigObject[value].
In Underscore this would look like this :
var keys = [ ... ]; // Keys from your big object
var obj = { ... }; // Your big object
var values = _.map(keys, function(value, index) {
return obj[value];
});
See this fiddle for experimenting.
Here's a solution using upcoming EcmaScript 7 Array Comprehensions available today via Babel.js.
Try it: Array Comprehensions Example.
ES7:
var obj = {
"key1": 1,
"key2": 2,
"key3": 3
}
var arr = ["key1"];
var values = [for(key of arr) obj[key]];
console.log(values);

How to get array key name using jQuery?

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.

Categories