How to add Key on existing array javascript - javascript

im currently working on a project that uses javascript as it's front end and im having a bit trouble on adding a key on my existing array.
i have an object that i wanted to be converted on array javascript.
here is my code on how to convert my object to array.
var obj = data[0];
var site_value = Object.keys(obj).map(function (key) { return obj[key]; });
var site_key = $.map( obj, function( value, key ) {
return key;
});
the site_value has the value of my objects.
the site_key has the key.
i want to add my site_key to the site_value array as a Key.
example data:
site_value:
0:Array[4]
0:Array[4]
1:Array[1]
2:Array[1]
3:Array[0]
site_key:
Array[49]
0:"AGB"
1:"BAK"
2:"BAN"
3:"BAR"
i want my array to be
AGB:Array[4]
0:Array[4]
1:Array[1]
2:Array[1]
3:Array[0]
Update:
Here is my object.
Array[1]0:
Object
AGB: Array[4]
BAK: Array[4]
BAN: Array[4]
etc.

You have almost done it and I have modified it a bit below to return it as array object,
var obj = data[0];
var site_value = Object.keys(obj).map(function (key) {
var output = {};
output[key] = obj[key];
return output;
});

I might be misunderstanding the question, sorry if I am. I think you would like to use a key "AGB" instead of an integer for an array index. In this case, you would probably be better served to use an object instead of an array. Maybe something like this
var myObject = {
AGB: Array[4],
AGBarrays: [Array[4],Array[1],Array[1],Array[0]]
};
Then you could access AGB by key and your additional arrays by index

Related

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

Get Key From Value in Key-Value Pair

I have something like this:
var input = [];
var result = {};
input.push({
key: 1,
value: Value
});
result[input[0].key] = input[0].value;
If I want to get the value from key i call result[key], but what if I want to get the Key from a certain value? Any ideas?
You could create an inverse mapping of values → keys; however, there is no guarantee that the values will be unique (whereas the keys must be), so you could map values → array of keys.
function inverseMap(obj) {
return Object.keys(obj).reduce(function(memo, key) {
var val = obj[key];
if (!memo[val]) { memo[val] = []; }
memo[val].push(key);
return memo;
}, {});
}
var a = {foo:'x', bar:'x', zip:'y'};
var b = inverseMap(a); // => {"x":["foo","bar"],"y":["zip"]}
[Update] If your values are definitely unique then you can simply do this:
function inverseMap(obj) {
return Object.keys(obj).reduce(function(memo, key) {
memo[obj[key]] = key;
return memo;
}, {});
}
inverseMap({a:1, b:2})); // => {"1":"a","2":"b"}
Of course, these solutions assume that the values are objects whose string representation makes sense (non-complex objects), since JavaScript objects can only use strings as keys.
A value might have several keys, so I'd recommend iterating over all the keys and adding those that have value into a list.
Do you plan to recurse for complex values?
You could use underscore.js's find method...
var key = _.find(result, function(val) {
return val === 'value';
}).key;
This will search your result for the value and return you the object, then you can grab the key off of it.
Underscore is one of my favorite tools for handling these kinds of things. There's lots of powerful methods in it.

Jquery fill object like array

This should be pretty easy but I'm a little confused here. I want to fill this object:
var obj = { 2:some1, 14:some2, three:some3, XX:some4, five:some5 };
but in the start I have this:
var obj = {};
I´m making a for but I don't know how to add, I was using push(), but is not working. Any help?
You can't .push() into a javascript OBJECT, since it uses custom keys instead of index. The way of doing this is pretty much like this:
var obj = {};
for (var k = 0; k<10; k++) {
obj['customkey'+k] = 'some'+k;
}
This would return:
obj {
customkey0 : 'some0',
customkey1 : 'some1',
customkey2 : 'some2',
...
}
Keep in mind, an array: ['some1','some2'] is basicly like and object:
{
0 : 'some1',
1 : 'some2'
}
Where an object replaces the "index" (0,1,etc) by a STRING key.
Hope this helps.
push() is for use in arrays, but you're creating a object.
You can add properties to an object in a few different ways:
obj.one = some1;
or
obj['one'] = some1;
I would write a simple function like this:
function pushVal(obj, value) {
var index = Object.size(obj);
//index is modified to be a string.
obj[index] = value;
}
Then in your code, when you want to add values to an object you can simply call:
for(var i=0; i<someArray.length; i++) {
pushVal(obj, someArray[i]);
}
For info on the size function I used, see here. Note, it is possible to use the index from the for loop, however, if you wanted to add multiple arrays to this one object, my method prevents conflicting indices.
EDIT
Seeing that you changed your keys in your questions example, in order to create the object, you can use the following:
function pushVal(obj, value, key) {
//index is modified to be a string.
obj[key] = value;
}
or
obj[key] = value;
I'm not sure how you determine your key value, so without that information, I can't write a solution to recreate the object, (as is, they appear random).

How do I change a JSON object into an array key/value pairs through code?

How do I change a JSON object into an array key/value pairs through code?
from:
{
'name':'JC',
'age':22
}
to:
['name':JC,'age':22] //actually, see UPDATE
UPDATE:
...I meant:
[{"name":"JC"},{"age":22}]
May be you only want understand how to iterate it:
var obj = { 'name':'JC', 'age':22 };
for (var key in obj)
{
alert(key + ' ' + obj[key]);
}
Update:
So you create an array as commented:
var obj = { 'name':'JC', 'age':22 };
var obj2 = [];
for (var key in obj)
{
var element = {};
element[key] = obj[key]; // Add name-key pair to object
obj2.push(element); // Store element in the new list
}
If you're trying to convert a JSON string into an object, you can use the built in JSON parser (although not in old browsers like IE7):
JSON.parse("{\"name\":\"JC\", \"age\":22}");
Note that you have to use double quotes for your JSON to be valid.
There is no associative array in JavaScript. Object literals are used instead. Your JSON object is such literal already.

Categories