I have This simple array :
var gdpData = {"CA": 1,"US": 2,"BF": 3,"DE": 4};
I want to find the value of BF using a loop
how can I do this by loop using JQuery or Javascript?
That's a object literal and not an array.
You can just call:
gdpData.BF // -> returns 3
You can
var res = gdpData["BF"];
or
var res = gdpData.BF;
You can also use the jquery each function
var gdpData = {"CA": 1,"US": 2,"BF": 3,"DE": 4};
jQuery.each(gdpData, function(key, value) {
if(key == "BF") {
alert(value)
}
})
for(var key in gdpData){
if(gdpData[key] == "BF") // do something ...
}
Note you have an object though, not an array. an object is more like a hashmap
Sure, you CAN use your own personal loop, but there's really not point because javascript does the hard work for you.
var obj = { 'a':1, 'b':2, 'c':3 };
var res = obj['a'];
But if you REALLY want to use a loop for some weird reason...
function findValue (obj, item) {
for (key in obj) {
if (key === item) {
return obj[key]; // OH LOOK - that's exactly the same thing.
}
}
return undefined;
}
var obj = { 'a':1, 'b':2, 'c':3 };
var res = findValue(obj, 'a');
Try this:
var gdpData = {"CA": 1,"US": 2,"BF": 3,"DE": 4};
for(var i in gdpData){
if("BF" === i){
alert(gdpData[i]);
}
}
sorry for the 'var'
Related
First, sorry if you find the question confusing.
Basically, I have an object like this:
[{"6":6.5},{"4":4.2},{"6":6.3}]
What I want to do, is to remove the duplicated keys but keep there values and push them all into one unique key only, as an array. like this:
[{"6":[6.5, 6.3]}, {"4": 4.2}]
Can anyone suggest a solution?
.reduce() is what you want:
var data = [{"6":6.5},{"4":4.2},{"6":6.3}];
var res = data.reduce((rv, obj) => {
var key = Object.keys(obj)[0];
rv[key] = rv[key] || [];
rv[key].push(obj[key]);
return rv;
}, {});
console.log(res);
Note: This returns data always in the format of arrays (Even if there is one value). If you're looking for the exact format you specified, you just need to add more logic as I've demonstrated below (Although, I wouldn't recommend this approach, as it adds more complication down the line.)
var data = [{"6":6.5},{"4":4.2},{"6":6.3}];
var res = data.reduce((rv, obj) => {
var key = Object.keys(obj)[0];
if (Array.isArray(rv[key])) { // Already is an array
rv[key].push(obj[key]);
} else if (rv[key] !== undefined) { // Has a value. Convert to array
rv[key] = [rv[key], obj[key]];
} else { // Haven't seen this key yet. Set the value
rv[key] = obj[key];
}
return rv;
}, {});
console.log(res);
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]);
});
This question already has answers here:
Javascript, Transforming object with underscore (or not)
(2 answers)
Closed 7 years ago.
Trying to change an object to prepare it for send by taking the array inside and turning it into an object with the items in the array being keys with values of true.
It starts out looking like -
{"state":["Saved","Published"],"discipline":["Marketing"]}
So the end result would look like
{"state":{"Saved":true,"Published":true},"discipline":{"Marketing":true}}
So it just looks at that array and changes it to an object with values of true. I am trying to use underscore but plain js would work just fine.
Here is my attempt, is there a better way to do this, maybe with underscore? -
function transformOutputToFilterModel(model) {
var transformedObj = _.map(model, function(obj) {
return obj.reduce(function(obj, k) {
obj[k] = true;
return obj;
}, {})
});
return transformedObj;
}
Thanks for reading!
Edit - sorry I had marked an answer wihtout realizing it wasn't exactly corret. I have this function -
var transformedObj = _.map(model, function(obj) {
return obj.reduce(function(obj, k) {
obj[k] = true;
return obj;
}, {});
});
this does format the inside object correctly, however it is pulling off the outer keys - see here : https://jsfiddle.net/d0kjctfh/3/
Those outer objecst should have the keys of state and discipline like this -
{"state":{"Saved":true,"Committed":false,"Published":false},"discipline":{"Marketing":true}};
Thanks!
You need to do it in several steps:
_.mapObject(model, function(vals) {
return _.object(vals, _.map(vals, function() { return true; }));
} );
The map just makes a list of trues the right length, the _.object changes ["Saved","Published"] into {"Saved":true,"Published":true} and the _.mapObject applies it to every field.
I think _.map will always return an array so its not the best solution. Try the code bellow.
var t = {"state":["Saved","Published"],"discipline":["Marketing"]},
newObj = {};
_.each(t, function(obj, index) {
newObj[index] = {};
if(_.isArray(obj)){
var toReturn = {};
_.each(obj, function(index,item){
toReturn[index] = true;
});
newObj[index] = toReturn;
}
});
console.log(newObj);
No need for underscore; Array.map() is native Javascript. However, map returns an array, which isn't what you want. Try reduce, accumulating the results into an (initially) empty object:
var input = {"state":["Saved","Published"],"discipline":["Marketing"]};
var toObject = function(arr) {
return arr.reduce(function(prev,curr){
prev[curr]=true;
return prev;
},{});
}
console.log(toObject(input.state));
var input = {"state":["Saved","Published"],"discipline":["Marketing"]};
function childToObj(arr) {
return arr.reduce(function(prev,curr){
prev[curr]=true;
return prev;
},{});
}
for (var key in input) {
if (input.hasOwnProperty(key)) {
input[key] = childToObj(input[key]);
}
}
console.log(input);
console.log(JSON.stringify(input));
Sometimes the easiest way is the classic way:
function prepareObject(obj){
var i, e, o = {};
for(e in obj){
if(obj.hasOwnProperty(e)){
o[e] = {};
for(i = 0; i <= obj[e].length - 1; i++) {
obj[e][obj[e][i]] = true;
}
}
}
return o;
}
Optimized / minify
window.prepareObject=function(b){var c,a,d={};for(a in b)if(b.hasOwnProperty(a))for(d[a]={},c=0;c<=b[a].length-1;c++)b[a][b[a][c]]=!0;return d};
I have an array like this:
var arrayTemp = [
{"0":["Z",59]},
{"1":["D",53]},
{"2":["6",26]},
{"3":["3",19]},
{"4":["Y",10]},
{"5":["H",7]},
{"6":["G",5]},
{"7":["2",5]}
];
I need an output similar to the below one,
var arrayTemp = [
{"Z":59},
{"D":53},
{"6":26},
{"3":19},
{"Y":10},
{"H":7},
{"G":5},
{"2":5}
];
How do I achieve this? I would like this to be achieved with the help of json, underscore or JavaScript.
Using Array.prototype.map() you could iterate trough each element of the original array and create the required objects, returning them as new elements in a new array.
var newArray = arrayTemp.map(function(e, index) {
var x = {};
x[e[index][0]] = e[index][1];
return x;
})
DEMO - Using Array.prototype.map() to create the new array
Something like this:
var newArray = arrayTemp.map(function(e) {
var index = Object.keys(e).shift(),
innerElement = e[index],
ret = {};
ret[innerElement[0]] = innerElement[1];
return ret;
})
JsFiddle to test.
With underscore:
var newArr = _.map(arrayTemp, function(item){
for (var i in item){
var o = {};
o[item[i][0]] = item[i][1];
return o;
}
});
Although #François_Wahl's solution is the better one in my esteem using the native Array.prototype.map().
Consider:
var object = {
foo: {},
bar: {},
baz: {}
}
How would I do this:
var first = object[0];
console.log(first);
Obviously, that doesn’t work because the first index is named foo,
not 0.
console.log(object['foo']);
works, but I don’t know it’s named foo. It could be named anything. I just want the first.
Just for fun this works in JS 1.8.5
var obj = {a: 1, b: 2, c: 3};
Object.keys(obj)[0]; // "a"
This matches the same order that you would see doing
for (o in obj) { ... }
If you want something concise try:
for (first in obj) break;
alert(first);
wrapped as a function:
function first(obj) {
for (var a in obj) return a;
}
they're not really ordered, but you can do:
var first;
for (var i in obj) {
if (obj.hasOwnProperty(i) && typeof(i) !== 'function') {
first = obj[i];
break;
}
}
the .hasOwnProperty() is important to ignore prototyped objects.
This will not give you the first one as javascript objects are unordered, however this is fine in some cases.
myObject[Object.keys(myObject)[0]]
If the order of the objects is significant, you should revise your JSON schema to store the objects in an array:
[
{"name":"foo", ...},
{"name":"bar", ...},
{"name":"baz", ...}
]
or maybe:
[
["foo", {}],
["bar", {}],
["baz", {}]
]
As Ben Alpert points out, properties of Javascript objects are unordered, and your code is broken if you expect them to enumerate in the same order that they are specified in the object literal—there is no "first" property.
for first key of object you can use
console.log(Object.keys(object)[0]);//print key's name
for value
console.log(object[Object.keys(object)[0]]);//print key's value
There is no way to get the first element, seeing as "hashes" (objects) in JavaScript have unordered properties. Your best bet is to store the keys in an array:
var keys = ["foo", "bar", "baz"];
Then use that to get the proper value:
object[keys[0]]
ES6
const [first] = Object.keys(obj)
Using underscore you can use _.pairs to get the first object entry as a key value pair as follows:
_.pairs(obj)[0]
Then the key would be available with a further [0] subscript, the value with [1]
I had the same problem yesterday. I solved it like this:
var obj = {
foo:{},
bar:{},
baz:{}
},
first = null,
key = null;
for (var key in obj) {
first = obj[key];
if(typeof(first) !== 'function') {
break;
}
}
// first is the first enumerated property, and key it's corresponding key.
Not the most elegant solution, and I am pretty sure that it may yield different results in different browsers (i.e. the specs says that enumeration is not required to enumerate the properties in the same order as they were defined). However, I only had a single property in my object so that was a non-issue. I just needed the first key.
You could do something like this:
var object = {
foo:{a:'first'},
bar:{},
baz:{}
}
function getAttributeByIndex(obj, index){
var i = 0;
for (var attr in obj){
if (index === i){
return obj[attr];
}
i++;
}
return null;
}
var first = getAttributeByIndex(object, 0); // returns the value of the
// first (0 index) attribute
// of the object ( {a:'first'} )
To get the first key of your object
const myObject = {
'foo1': { name: 'myNam1' },
'foo2': { name: 'myNam2' }
}
const result = Object.keys(myObject)[0];
// result will return 'foo1'
Based on CMS answer. I don't get the value directly, instead I take the key at its index and use this to get the value:
Object.keyAt = function(obj, index) {
var i = 0;
for (var key in obj) {
if ((index || 0) === i++) return key;
}
};
var obj = {
foo: '1st',
bar: '2nd',
baz: '3rd'
};
var key = Object.keyAt(obj, 1);
var val = obj[key];
console.log(key); // => 'bar'
console.log(val); // => '2nd'
My solution:
Object.prototype.__index = function(index)
{
var i = -1;
for (var key in this)
{
if (this.hasOwnProperty(key) && typeof(this[key])!=='function')
++i;
if (i >= index)
return this[key];
}
return null;
}
aObj = {'jack':3, 'peter':4, '5':'col', 'kk':function(){alert('hell');}, 'till':'ding'};
alert(aObj.__index(4));