I have a object map in JavaScript and I have to read it.
The object map is:
network[0]
Object {dpi: "user2"}
I have used this to read the key:
demp=Object.keys(network[0]);
sourceNodeFirewall = demp[0];
But I'm not able to read the value ("user2").
I know that I can do this:
network[0].dpi
in order to have user2, but during a for cycle I have no idea to do it, in addition that the key can change in any value.
I cannot put the real code because it is very complicate but an simple example is:
The object is set in this way:
var network = {};
network[$("#0B").val()] = $("#0BB").val();
Where I have a key and I value.
After that I wish to get the value and the key.
demp stores all key of the object, You need to access the property from the network[0] object.
var network = [{dpi: "user2"}];
demp = Object.keys(network[0]);
console.log(network[0][demp[0]]);
You can access an object's properties by indexing into it with square brackets:
var network = [{dpi: "user2"}];
console.log(network[0]);
var demp = Object.keys(network[0]);
var sourceNodeFirewall = demp[0];
var propValue = network[0][demp[0]];
console.log(propValue);
In a for loop you need to iterate over each key in the map, and to access the value just lookup the map with that key as the index.
var network = {
dpi: "user2"
}
for (var key in network) {
console.log(network[key]);
}
As you referred to a for loop, here what I think you are looking for:
const obj = {
dpi: "user2"
};
for(key in obj){
console.log(obj[key]);
}
Or maybe using a forEach:
const obj = {
dpi: "user2"
};
Object.keys(obj).forEach(
key => console.log(obj[key])
)
Related
I am still somewhat new to JavaScript, Node, etc. and come from a Groovy background (which has extremely similar syntax to JavaScript). In Groovy, I can easily do something like this:
def myMap1 = {};
def myMap2 = {};
myMap1["key1"] = "value1";
myMap1["key2"] = "value2";
myMap1["key3"] = "value3";
myMap1.each() { key, value =>
myMap2[key] = value;
}
This would iterate through the existing map (myMap1) and copy the values for each key to the new map (myMap2), with the same key names. Easy as pie. However, JS has a concept of the prototype, which has been driving me crazy because you have to use hasOwnProperty, the index of the item sort of thing, etc and it results in a lot of code for something that's supposed to be really simple.
Looking at the MDN docs for Object(), it looks like JS has implemented something that allows a developer to access key/value pairs without having to deal with prototyping and all of that stuff, and you can just access the data in the object, and not properties of the object. I now have this:
var existingData = {"foo":"thing","bar":"otherThing","baz":"whatever"};
var update = {"foo":"newStuff","bar":"thisChanged","baz":"arghh"};
for (const [ key, value ] of Object.entries(update)) {
console.log("Old value is " + existingData[key]);
existingData[key] = value;
console.log("Setting " + existingData[key] + " to " + value);
}
I would think this would work, but I get this in the console instead:
Old value is undefined
Setting thing to thing
Old value is undefined
Setting otherThing to otherThing
Old value is undefined
Setting whatever to whatever
It looks like existingData[key] does not reference the key in the key/value pair, but instead the value or something? How do I tell it, "for this key name in this second object, set this value?" I've been searching forever on Google and everything is either doing it the old way (with indexes) or is overly complicated for no particular reason. Any help would be greatly appreciated.
for (let key in map1) {
map2[key] = map1[key];
}
BTW why you dont use Object.assign(); ? (notice: it returns a new object)
let update = { "key1": "value1", "key2": "value2" };
let map2 = Object.assign({}, map1, update);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
Simply use Object.assign(map2, map1) to update map2 (copy key/value of map1 to map2)
Or you can use,
map2 = {...map2, ...map1} to build a new object and replace the map2 completely
To have a deep copy, instead of only first level you can use JSON.parse(JSON.stringify(map2)) instead of map2. If you think, its a large object and that impact performance, go for a nested implementation of copy recursively! ;-)
You could just do this - looping through an array of the keys:
let myMap1 = {};
let myMap2 = {};
myMap1["key1"] = "value1";
myMap1["key2"] = "value2";
myMap1["key3"] = "value3";
// create an array of the keys in the object myMap1
let myMap1_keys = Object.keys(myMap1);
// loop through the array of object keys
for (let i = 0; i < myMap1_keys.length; i++) {
myMap2[myMap1_keys[i]] = myMap1[myMap1_keys[i]];
}
I would advise not using a for..in loop i.e. as used in one of the other answers as these are slower than a native for loop (as used above). You can see some details regarding performance here: Comparing JavaScript loops performance (for, do while, for in)
If you are just interested in literally duplicating the object you can do that like so:
let myMap2 = JSON.parse(JSON.stringify(myMap1));
Anouther answer suggested using Object.assign() and anouther suggested using ES6 spread operators but these will 'shallow' copy the object which means the objects are using references to the original object and will only copy the top level of the object - the method above deep copies the object which I usually find is what is required for most use cases and will copy every level of the object.
You can iterate over keys. check is this helpful to you
var m1 = {};
let m2 = {};
m1["key1"] = "abc";
m1["key2"] = "def";
m1["key3"] = "ghi";
var m1_change_key = Object.keys(m1);
for (var i = 0; i < m1_change_key.length; i++) {
m2[m1_change_key[i]] = m1[m1_change_key[i]];
alert(m2[m1_change_key[i]])
}
I'm not sure if it's possible or not. So here I'm looking for an answer.
Is there any way to declare an object like:
var objectName = {
key1 : 'value1',
key2,key3 : 'value2;
}
I'm trying to combine key2 and key3 together.
If you don't want to assign the values like Patric Roberts says, create an array of keys and set the same value to those keys like so:
var obj = {};
obj['key1'] = 1;
// Array of keys
var arrayOfKeys = ['key2','key3','key4'];
// Common value for keys in array
var val = 2;
// Iterate the array
for(var k in arrayOfKeys) {
obj[arrayOfKeys[k]] = val;
}
console.log(obj);
You can also check this answer
You could use a slightly different approach, which will work on primitive values, too, by adding an object for keeping the same reference to different keys in the array. For example, you have a value object, like
temp = {
value: 42
}
and an array, like
object = {
key2: temp,
key3: temp
}
then you can use the keys independently for the value of the referenced object.
To change the value, you need to address it with
object.key2.value = 2000;
console.log(object.key3.value); // 2000
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
How can I get the value of an object with an unknown single key?
Example:
var obj = {dbm: -45}
I want to get the -45 value without knowing its key.
I know that I can loop over the object keys (which is always one).
for (var key in objects) {
var value = objects[key];
}
But I would like to know if there is a cleaner solution for this?
Object.keys might be a solution:
Object.keys({ dbm: -45}); // ["dbm"]
The differences between for-in and Object.keys is that Object.keys returns all own key names and for-in can be used to iterate over all own and inherited key names of an object.
As James Brierley commented below you can assign an unknown property of an object in this fashion:
var obj = { dbm:-45 };
var unkownKey = Object.keys(obj)[0];
obj[unkownKey] = 52;
But you have to keep in mind that assigning a property that Object.keys returns key name in some order of might be error-prone.
There's a new option now: Object.values. So if you know the object will have just one property:
const array = Object.values(obj)[0];
Live Example:
const json = '{"EXAMPLE": [ "example1","example2","example3","example4" ]}';
const obj = JSON.parse(json);
const array = Object.values(obj)[0];
console.log(array);
If you need to know the name of the property as well, there's Object.entries and destructuring:
const [name, array] = Object.entries(obj)[0];
Live Example:
const json = '{"EXAMPLE": [ "example1","example2","example3","example4" ]}';
const obj = JSON.parse(json);
const [name, array] = Object.entries(obj)[0];
console.log(name);
console.log(array);
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"}