This question already has answers here:
Is it possible to add dynamically named properties to JavaScript object?
(20 answers)
Closed 6 years ago.
I am using this slice of code (shown below) in an attempt to populate the object literal named Parameters inside the for loop. I need the key:value pair to be assigned in conjunction with the loops iterating i variable, as such: {key_1:chunks[1],key_2:chunks[2]}. However, my code isn't working. The 'key_'+i is not being reflected in the literal.
There's something I am missing here, obviously. Can someone tell me what it is?...Thanks.
var Parameters=[];
var len = chunks.length;
for (var i = 0; i < len; i++) {
var key='key_'+i
obj= { key : chunks[i]};
Parameters.push(obj)
}
EDIT: Use var obj = {}; obj[key] = chunks[i];
Because ECMAScript treats the key in this {key:1} as literal.
ES2015 (via Babel) Supports dynamic keys:
const Parameters=[];
const len = chunks.length;
for (let i = 0; i < len; i++) {
const key = `key_${i}`;
obj = { [key] : chunks[i]};
Parameters.push(obj);
}
(note the brackets around the key)
Or better yet:
const Parameters = chunks.map((c, i) => ({ [`key_${i}`]: c }));
same can be used for lookup: obj[key] . Do remmeber obj.key will look for key in object
var obj = {
test:1
}
var key = 'test'
obj.test = obj[key] = 1
Here obj.key will not work
Related
This question already has answers here:
Push Object in Array [duplicate]
(2 answers)
Closed 4 years ago.
const maxObj = [{"BTCH#BD":57887,"BTYPEBD":"OCO"},
{"BTCH#BD":57887,"BTYPEBD":"OCO"},
{"BTCH#BD":57890,"BTYPEBD":"OTH"}]
const req = "4976809";
const result = [];
const temp = { reqId: req, batch: null };
for (var x = 0; x < maxObj.length; x++) {
temp.batch = maxObj[x];
result.push(temp);
}
console.log(JSON.stringify(result));
In this code I'm trying to iterate through an an array of objects and assigning each object to the property of a temporary template object that I then push to the results array. My expected output is something like this:
[{"reqId":"4976809","batch":{"BTCH#BD":57887,"BTYPEBD":"OCO"}},
{"reqId":"4976809","batch":{"BTCH#BD":57887,"BTYPEBD":"OCO"}},
{"reqId":"4976809","batch":{"BTCH#BD":57890,"BTYPEBD":"OTH"}}]
But my actual output is like this:
[{"reqId":"4976809","batch":{"BTCH#BD":57890,"BTYPEBD":"OTH"}},
{"reqId":"4976809","batch":{"BTCH#BD":57890,"BTYPEBD":"OTH"}},
{"reqId":"4976809","batch":{"BTCH#BD":57890,"BTYPEBD":"OTH"}}]
How do I fix this so I get the expected output above?
You use the same object for pushing. You get same objects inside of the array.
You could use a new object with wanted property to prevent to store the same object reference.
const maxObj = [{"BTCH#BD":57887,"BTYPEBD":"OCO"},
{"BTCH#BD":57887,"BTYPEBD":"OCO"},
{"BTCH#BD":57890,"BTYPEBD":"OTH"}]
const req = "4976809";
const result = [];
for (var x = 0; x < maxObj.length; x++) {
result.push({ reqId: req, batch: maxObj[x] });
}
console.log(JSON.stringify(result));
function removeDupes() {
var out = [],
obj = {};
for (x = 0; x < intArray.length; x++) {
obj[intArray[x]] = 1;
}
for (x in obj) {
out.push(x);
}
return out;
}
hi all, obj { } is supposed to have been declared as an object, but why putting [ ] and using obj as array works? thanks
someObject["somePropertyName"] is how you access the property of an object. (You can also use someObject.somePropertyName but only if the property name is a valid identifier).
The syntax has nothing specifically to do with arrays.
Arrays are just a type of object with a bunch of methods that treat property names that are integer numbers in special ways.
(Numbers are not valid identifiers so you must use the square bracket syntax to access properties with names that are numbers).
First of all, let's fix your removedDupes function by adding intArray as an argument and declaring the loop iterators as local variables var x:
function removeDupes(intArray) {
var out = [],
obj = {};
for (var x = 0; x < intArray.length; x++) {
obj[intArray[x]] = 1;
}
for (var x in obj) {
out.push(x);
}
return out;
}
The first loop iterates over all intArray elements. For each element it creates a new property on obj with key intArray[x] and value 1 via obj[intArray[x]] = 1. This is called bracket notation. Now, objects can't have duplicate keys. So adding the same property key twice actually overrides the previously added property. Thus, when the loop completes, your obj has exactly one key per unique array element.
The second loop then pushes these keys into the resulting out array.
There are some issues with your removeDupes function. Firstly, it returns an array of string elements even though the input is an array of number elements. This is because obj keys can't be numbers and are always converted to strings. You can fix it by storing the numeric values along with the keys as follows:
function removeDupes(intArray) {
var out = [],
obj = {};
for (var x = 0; x < intArray.length; x++) {
obj[intArray[x]] = intArray[x];
}
for (var x in obj) {
out.push(obj[x]);
}
return out;
}
Now, this works, but it is very verbose. You can make it shorter by replacing the second loop with return Object.values(obj);. Or even shorter by using a Set:
function removeDupes(intArray) {
return [...new Set(intArray)];
}
This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 5 years ago.
I have one array which have all the properties of values for object .
something like this.
var act=["name.first","age"];
var ab={name:{first:"roli",last:"agrawal"},age:24};
console.log(ab[act[0]]);
how to access value of object using act values?
You have to split the string act[0] as your object does not contain any key named "name.first":
var act=["name.first","age"];
var ab={name:{first:"roli",last:"agrawal"},age:24};
var key = act[0].split('.');
console.log(ab[key[0]][key[1]]);
try this simple
var ab = {first: 'a',
last: 'b',
age: '24'}
var ac = [];
ac.push(ab);
console.log(ac[0]);
Agree that it isn't natively supported, but you can use a little rectifier function to iterate down the passed path and get the value. This could probably be optimized, but works:
var act=["name.first","age"];
var ab={name:{first:"roli",last:"agrawal"},age:24};
function getProperty(inputObj, path) {
var pathArr = path.split('.');
var currentObjLevelOrOutput;
var i;
if (pathArr.length > 1) {
currentObjLevelOrOutput = inputObj;
for (i=0; i < pathArr.length; i++) {
currentObjLevelOrOutput = currentObjLevelOrOutput[pathArr[i]];
}
} else {
currentObjLevelOrOutput = inputObj[path];
}
return currentObjLevelOrOutput;
}
console.log(getProperty(ab,act[0]));
This question already has answers here:
Convert JavaScript array of 2 element arrays into object key value pairs
(5 answers)
Closed 7 years ago.
I have an array that looks something like this: [["key1", "value1"], ["key2", "value2"]]. I want a dictionary that looks like this: {"key1": "value1", "key2": "value2"}. In Python, I could just pass the array to the dict initializer. Is there some equivalent way of doing this in Javascript, or am I stuck initializing an empty dictionary and adding the key/value pairs to the dictionary one at a time?
It's actually really easy with Array#reduce:
var obj = yourArray.reduce(function(obj, entry) {
obj[entry[0]] = entry[1];
return obj;
}, {});
Array#reduce loops through the entries in the array, passing them repeatedly into a function along with an "accumulator" you initialize with a second argument.
Or perhaps Array#forEach would be clearer and more concise in this case:
var obj = {};
yourArray.forEach(function(entry) {
obj[entry[0]] = entry[1];
});
Or there's the simple for loop:
var obj = {};
var index, entry;
for (index = 0; index < yourArray.length; ++index) {
entry = yourArray[index];
obj[entry[0]] = entry[1];
}
Assuming you have a pairs variable, you can use a map() function workaround (not very elegant, as map is supposed to be used in other scope) :
var convertedDict = {};
pairs.map(function(pair) {
convertedDict[pair[0]] = pair[1];
});
I'm trying to add a key value pair to an existing javascript associative array. The key needs to be a variable. This is for JSON encoding. I realize there are many plugins and frameworks for this, but I want a simple answer.
ary.push({name: val});
where ary is a new array, name is a variable containing the key, val is the value of this entry.
I'm doing this in a jQuery loop that iterates through form fields.
In ES6...
In ES6, you can use a destructuring assignment;
ary.push({[name]: val});
However, given this is ES6 syntax, the usual caveats apply; this will not work in some browsers (noticably, IE and Edge 13)... although Babel will transpile this for you.
Without ES6 (legacy browser support)...
You need to define an object and use square bracket notation to set the property;
var obj = {};
obj[name] = val;
ary.push(obj);
If you get the urge to read into it more, see this article on the differences between square bracket and dot notation.
var ary = [];
function pushToAry(name, val) {
var obj = {};
obj[name] = val;
ary.push(obj);
}
pushToAry("myName", "myVal");
Having just fully read your question though, all you need is the following
$(your collection of form els).serializeArray();
Good old jQuery
An "associative array" is really just an object. You don't use push, you just assign properties to the object:
ary[name] = val;
The following code will help you
ary.push( {[name]: val} );
See below example
let allData = [{name: "Cat", type: "Animal"}]
let finalData: any = [];
for (let i = 0; i < allData.length; i++)
{
let obj = allData[i];
for (let KEY in obj)
{
//Pushing data to other array as object
this.finalData.push({ [KEY] : obj[KEY] });
}
}
const tStyles = [];
for (const i of iStyles) {
const temp = {};
temp[`${style}`] = `../dist/css/uikit.${wFile}.${style}.css`;
tStyles.push(temp);
}
json : {"black-beige":"../dist/css/uikit.or.black-beige.css"}