How do I create an object from two array indexes? - javascript

I am trying to create a javascript object with two array indexes, but it does not seem possible. Why is that? For example:
var arr = ["name","john"];
var obj = {arr[0]:arr[1]}

Computed property names need brackets [myPropName]
var arr = ["name","john"]
var obj = {[arr[0]]:arr[1]}
obj.name // 'john'

You can also do Object.assign,
var arr = ["name","john"];
var obj = {};
var newObj = Object.assign(obj, {[arr[0]]: arr[1]});
console.log(newObj);

If you use arr[0] then js will understand that the property name is arr[0] not "name", so you need [arr[0]] for it to interpret as "name"
var obj = {[arr[0]]:arr[1]}

Related

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

Can't access array by named key in JavaScript

I need to pass an array of objects to a php page as part of a larger data structure. I am trying to replicate this structure in JavaScript and pass it via json.
The arrays keys in php have been set as names which I require later in the process.
I know JavaScript doesn't use associated arrays and arrays in JavaScript are essentially objects but documentation suggests I should be able to use named keys.
If this is the case I should also be able to use variables as named keys by using a different syntax.
Can someone then please show me what I am doing wrong?
Example 1: numeric keys (works)
var dataTargets = [];
var obj = {
'test': 'test'
};
dataTargets["0"] = obj;
alert(JSON.stringify(dataTargets));
Example 2: named keys (fails)
var dataTargets = [];
var obj = {
'test': 'test'
};
dataTargets["test"] = obj;
alert(JSON.stringify(dataTargets));
//outputs []
Example 3: variable keys (fails)
var dataTargets = [];
var dtname = "test";
var obj = {
'test': 'test'
};
dataTargets[dtname] = obj;
alert(JSON.stringify(dataTargets));
//outputs []
The properties are actually being correctly assigned to each array; the problem is that JSON.stringify ignores all non-index properties of arrays (treating them more like lists and less like objects). If you want to use named keys in your objects, you will have to use plain objects {} rather than arrays []:
var alert = console.log.bind(console) // for demo purposes
// Example 1: numeric keys
var dataTargets = {};
var obj = {'test':'test'};
dataTargets["0"] = obj;
alert(JSON.stringify(dataTargets));
// Example 2: named keys
var dataTargets = {};
var obj = {'test':'test'};
dataTargets["test"] = obj;
alert(JSON.stringify(dataTargets));
// Example 3: variable keys
var dataTargets = {};
var dtname = "test";
var obj = {'test':'test'};
dataTargets[dtname] = obj;
alert(JSON.stringify(dataTargets));
//outputs []
what you did actually like this
example1:
var dataTargets = [];
var obj = {'test':'test'};
dataTargets[0] = obj;
alert(JSON.stringify(dataTargets));
// outputs [{test:test}]
what you need is:
var dataTargets = {};
var obj = {'test':'test'};
dataTargets["test"] = obj;
alert(JSON.stringify(dataTargets));
//{"test":{{test:test}}}
because array need to be access by index. And object can be what you need

Key Value pair from an array with key Value pair in javascript

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().

create dynamic multi-dimenstional associative array using javascript

Below is my JS code :
var checkedLength = $(ele).parent().parent().find('table').find(':checkbox:checked').length;
if(checkedLength)
{
$(ele).parent().parent().find('table').find(':checkbox:checked').each(function(i) {
$(this).parent().removeClass().addClass('play');
$(this).prop('checked',false);
var agn = $(this).data('agn');
var value = $(this).data('kid');
checkedValues[agn] = {};
// Make bar an array, if it's not defined yet
checkedValues[agn]["bar"] = checkedValues[agn]["bar"] || [];
checkedValues[agn]["bar"].push(value);
});
console.log(checkedValues);
}
From above code am getting output as :
object {agnName => bar[0] = 6}
Desired O/P :
object {agnName => bar[0] = 4,bar[1] = 5 , bar[2]=> 6}
Can anyone guide me how can achieve this array structure ??
Thanks.
You have a test to see if checkedValues[agn] exists and you create it as an empty object if it doesn't. However you then immediately try to push to an array within that object that doesn't exist
Try changing
checkedValues[agn] = {};
checkedValues[agn]['pl'].push = $(this).data('kid');
To
checkedValues[agn] = {pl:[]};/* add property "pl" who's value is empty array*/
/* now the array exists , can push elements into it*/
checkedValues[agn]['pl'].push($(this).data('kid'));
Also note push() syntax you are using is incorrect.....should be push( value )
You want an object, not an array:
checkedValues = {};
checkedValues.foo = {};
checkedValues.foo.bar = 'baz';
// Another way:
checkedValues["keyname"] = "value";
// You can also use variables as keys
var agn = "foo";
checkedValues[agn] = "value";
// Just don't forget to init nested objects
var agn = "foo";
checkedValues[agn] = {};
checkedValues[agn]["bar"] = "value";
// If you need an array inside:
var agn = "foo";
checkedValues[agn] = {};
// Make bar an array, if it's not defined yet
checkedValues[agn]["bar"] = checkedValues[agn]["bar"] || [];
checkedValues[agn]["bar"].push("value");
associative arrays are done as objects in Javascript:
var data = {
agnName: {
pl: [4, 5, 6]
}
}
so you can access data.agnName.pl[0] to return 4 or more dynamically with data['agnName'].pl[0]
To create a mulch-dimensional obj. you have to initialize obj and then you can enter value. like below
var obj = {}
obj[dynamicval1] = {};
obj[dynamicval1][dynamicval2] = {};
obj[dynamicval1][dynamicval2] = {key1:value1,key2:value2};
Hope it works!

declare hashmap in javascript with <String,String array>

I want to declare a hashmap in javascript with <String, String array> instead of <String,Integer>. How can that be done ?
If you plan to use a javascript Array object, be aware that an array index can only be accessed via integers.
var arr = [];
arr['person'] = 'John Smith';
alert(arr.length); // returns 0, not an array anymore;
and
var arr = [];
arr[0] = 'John Smith';
alert(arr.length); // returns 1, still an array;
The above would work in javascript, but var arr actually is not an array object anymore. You cannot sort it, for example.
So for you hashmap you could do
var map = new Object();
map['person'] = [];
map['person']['test'] = 'myvalue';
map['person']['test2'] = 'myvalue2';
alert(map['person']['test']);

Categories