Say I have a code like this:
var object = {
property_1:'value_1'
}
var arr = [object]
I want to be able to get an object name returned as a string. So it would look something like this:
arr[0].name /*return 'object'*/
or
arr[0].property_1.objectName /*return 'object'*/
This obviously isn't a valid code, but is there any that could actually do this?
It's not possible to do what you want. However, you could do the following:
var objects = {
object1: {
property_1:'value_1'
},
object2: {
property_1:'value_2'
}
};
// Use this to get an array with the names
function getNames() {
return Object.keys(objects);
}
// Use this to get the properties of an object by it's given name
function getProps(name) {
return objects[name];
}
Execution example:
var names = getNames();
for(i = 0; i < names.length; i++) {
var name = names[i];
var values = getProps(name);
console.log(name);
console.log(values);
console.log(values.property_1);
}
Output:
object1
{property_1: "value_1"}
value_1
object2
{property_1: "value_2"}
value_2
All this considering you are using ES5.
With ES6 you could simply do the following to get a list of object names and properties:
Object.keys(objects).map(key => ({name: key, properties: objects[key]}))
I hope this helps you in some way!
is there any that could actually do this?
No. var object is not what you are assigning to the array, the content of it is what you assigned.
var object = {
property_1:'value_1'
}
var arr = [object]
Is the same as:
var object1 = {
property_1:'value_1'
}
var object2 = object1;
arr = [object2];
and in the second example object1, object2 and arr[0] all point to the same object, and that object has no name.
Related
This was my initial solution, but I discovered that Object.keys does not work with an array index.
let myArrayForObjects = [];
function firstFunc(){
myArrayForObjects.push(object1, object2, object3);
}
function secondFunc(){
for (let i = 0; i < myArrayForObjects.length; i++){
let varName = Object.keys({myArrayForObjects[i]}[0]);
console.log(varName);
}
}
I posted it as here and was suggested the following solution:
let myArrayForObjects = [];
function firstFunc(){
myArrayForObjects.push(object1, object2, object3);
}
function secondFunc(){
for (let i = 0; i < myArrayForObjects.length; i++){
// Find the object in the array
let objectIndex = myArrayForObjects.indexOf(myArrayForObjects[i]);
// Get the object's name
let objectName = Object.keys(myArrayForObjects)[objectIndex];
console.log(objectName);
}
}
But that logs 1, 2 and 3 to the console. And what I want it to log is object1, oject2, and object3.
Is it even possible to do what I want? Or should I just add a property to the object with its name?
Instead of storing the objects in an array, put them in an object like so:
const myObjects = { object1, object2, object3 }
You can now either access them by name:
console.log(myObjects.object1)
Or iterate on the objects if needed:
console.log(Object.values(myObjects))
I want to push my object without a key in my javascript array. Right now the issue is I psuh my object in the array, but I add extra key 0,1,2 ... I don't want that key. Is there any solution for that? Here I add the code that I implemented.
let newArr = [];
let myId = data['id'];
var key = myId;
var obj = {};
myobj[key] = {
data: "testdata"
};
newArr.push(myobj);
The above code generates output like below. I don't want that 0 key in my array
0: {
260: {
data: 'testdata'
},
}
It's hard to tell what you're wanting, but I expect you don't want to be using an array here at all? You just want a single object that contains all of your key-value pairs?
e.g. something like this:
const data = { id: 1234 };
let myId = data['id'];
var key = myId;
var myobj = {};
myobj[key] = {
data: "testdata"
};
console.log(myobj);
// You can then add more data
myobj[2345] = {
data: "more test data"
};
console.log(myobj);
// Example Property Access
console.log(myobj[2345])
Try this
newArr.push(...myobj);
I have this code.
I want to set objects dynamically with the value of an array inside other object
var object1 = {repetidos : {}};
var object2 = {nombre: 'Example', precio: 'Example 2', etc...};
//Object with the array
var carga = {
repetidos : ['nombre','precio']
}
// custom function to set objects... I don't want to return nothing
cargaDatos(object1,object2,carga);
// Here is the function that i'm trying to code
cargaDatos = function(object1,object2,carga){
// what can i do here?. I have tried to use for loops
for(var key in carga){
for(var key2 in key){
//Here I have tried many things
}
}
}
//////////////////////////////////////////////////////////
// I want set something like this inside the function
object1.repetidos.nombre = object2.nombre; // nombre is variable
object1.repetidos.precio = object2.precio; // precio is variable
etc ....
What can I do to set the objects like above with variable values?
You can use the [] notation of objects.
var object1 = {
repetidos: {}
};
var object2 = {
nombre: 'Example',
precio: 'Example 2'
};
//Object with the array
var carga = {
repetidos: ['nombre', 'precio']
};
// Here is the function that i'm trying to code
var cargaDatos = function(object1, object2, carga) {
// what can i do here?. I have tried to use for loops
for (var key in carga) {
for (var key2 in carga[key]) {
// since carga[key] is an array key2 refers to the index
var actualKey2 = carga[key][key2];
object1[key][actualKey2] = object2[actualKey2];
}
}
}
// custom function to set objects... I don't want to return nothing
cargaDatos(object1, object2, carga);
//test
console.log(object1);
You need to use bracket notation to dynamically access the objects elements:
cargaDatos(object1,object2,carga);
function cargaDatos(object1,object2,carga){
for(var key in carga){
for(var key2 in key){
object1[key][carga[key][key2]] = object2[carga[key][key2]];
}
}
}
console.log(object1);
Also note, that i changed var cargaDatos = function.... to function cargaDatos because otherwise you need to declare var cargaDatos before you use it. If you just use function cargaDatos it doesn't matter if you declare it before or after you use it.
NOTE: if you want to dynamically fill the entire object1 you have to ensure that the element key exists on object1:
for(var key in carga){
for(var key2 in key){
if(!object1[key])object1[key] = {};
object1[key][carga[key][key2]] = object2[carga[key][key2]];
}
}
The main thing to understand is you can access object properties with dynamic keys by obj[key]. To traverse the array you can also use foreach..
cargaDatos = function(object1,object2,carga){
for(var key in carga){
carga[key].forEach(function(x){
object1[key][x] = object2[x];
});
}
}
I have an array like this:
var myArray = new Array();
myArray['foo'] = {
Obj: {
key: value
}
};
myArray['bar'] = {
Obj: {
key: value
}
};
When I do console.log(myArray) I just get empty [ ]. And when I try to iterate the array using jQuery's each the function doesn't run.
How can I get the 'foo' and 'bar' parts of the array?
Example code:
console.log(myArray); // [ ]
jQuery.each(myArray, function(key, obj) {
console.log(key); // should be 'foo' following by 'bar'
});
In addition, why does this work:
jQuery.each(myArray[foo], function(obj, values) {
// Why does this work if there are no associative arrays in JS?
});
you can get keys by:
Object.keys(variable name);
it returns array of keys.
You need to define it as an object if you want to access it like that:
var myObj= {};
myObj.foo = ...;
myObj.bar = ...;
Now you can access the properties like myObj["bar"] or myObj.bar
Note:
To loop through all the properties it's wise to add an additional check. This is to prevent you from looping through inherited properties.
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
// Do stuff.
}
}
Array is a collection where each element has an index.
To add element to array you can use push method
myArray.push('someValue');
or set element by index (if length of array < index):
myArray.push('someValue1');
myArray.push('someValue1');
myArray[0] = 'new someValue1';
Note that array is an instance of Object class, so you can add/edit any property of this object:
myArray.foo = '1';
myArray['bar'] = '2';
In this case you will not add new element to array, you defining new properties of object.
And you don't need to create object as Array if you don't wont to use indexes.
To create new object use this code:
var myObj = {};
To get all properties of object see
How to get all properties values of a Javascript Object (without knowing the keys)?
var myArray = {};
myArray['foo'] = { 'key': 'value' }
myArray['bar'] ={ 'key': 'value' }
console.log(myArray)
jQuery.each(myArray['foo'], function(obj, values) {
console.log(obj, values)
});
Demo
With your Array of Objects you could use this function:
var getKeys = function(obj) {
if (!(typeof obj == "object")) return [];
var keys = [];
for (var key in obj) if (obj != null && hasOwnProperty.call(obj, key)) keys.push(key);
return keys;
};
getKeys(myArray) would give you an array of your Keys.
This is basically a cleared up version of underscores _.keys(myArray) function. You should consider using underscore.
// $.each() function can be used to iterate over any collection, whether it is an object or an array.
var myArray = {};
myArray['alfa'] = 0;
myArray['beta'] = 1;
$.each(myArray, function(key, value) {
alert(key);
});
Note: checkout http://api.jquery.com/jQuery.each/ for more information.
I would like to create a structure within javascript. I have a pair of informations, I would like to use, example:
array[1] = new Struct();
array[1].name = "parameter-name";
array[1].value = "parameter-value";
array[2] = new Struct();
array[2].name = "parameter-name2";
array[2].value = "parameter-value2";
This can be on a diffrent page with diffrent values, maybe on element within my array, maybe 2-20..
Later, within my generic javascript, I would like to parse the array and continue with my parameters, example:
for(i=1 to length_of_my_array) {
_tag.array[i].name = array[i].value;
}
How can I realize this with pure javascript? Thanks for any hint!
As long as you don't want any fancy features, it's really easy to create such structures in JavaScript. In fact, the code you posted will almost work, if you replace the new Struct() with this:
array[1] = {};
This creates an empty object, and you can put any properties you want in it, such as name and value.
To create an array, you can do something like this:
var array = []; // empty array
// object literal notation to create your structures
array.push({ name: 'abc', value: 'def' });
array.push({ name: 'ghi', value: 'jkl' });
...
And to iterate over the array:
for (var i = 0; i < array.length; i++) {
// use array[i] here
}
It would be good to find out more regarding the problem you are attempting to resolve.
I don't think there is an object in JavaScript called Struct, unless you define one.
I think what you are looking for is a JavaScript object instead of Struct. There are a number of ways to create a new object, and they can be nested in an array or in other objects.
myArray[0] = new Object();
myArray[0].name = "parameter-name";
myArray[0].value = "parameter-value";
myArray[1] = new Object();
myArray[1].name = "parameter-name2";
myArray[1].value = "parameter-value2";
Notice that I have changed your code in a couple of ways:
1. "array" is named "myArray" to clarify that we are referring to a particular array.
2. The first instance of myArray is 0. Arrays start at 0 in Javascript.
3. Struct is changed to Object.
myarray = [
{
"name":"parameter-name",
"value":"parameter-value"
},
{
"name":"parameter-name2",
"value":"parameter-value2"
}
];
This is an alternative syntax for doing the same thing. It uses "literal notation" to designate an array (the square brackets), and the objects (the curly brackets).
for(var i = 0; i < myArray.length; i++) {
for(key in myArray[i]) {
alert(key + " :: " myArray[i][key]);
}
}
This will loop over the array and alert you for each property of the object.
alert(myArray[0]['value']) //parameter-value
myArray[0]['value'] = "bar";
alert(myArray[0]['value']) //bar
Each property of each object can also be assigned a new value.
You can define arrays and generic objects in pure JavaScript/json:
var array = []; // empty array
array.push({name: 'parameter-name', value: 'parameter-value'});
array.push({name: 'parameter-name2', value: 'parameter-value2'});
console.log(array);
// Output:
// [Object { name="parameter-name", value="parameter-value2"}, Object { name="parameter-name2", value="parameter-value2"}]
You can also define the same array like so:
var array = [
{name: 'parameter-name', value: 'parameter-value'},
{name: 'parameter-name2', value: 'parameter-value2'}
];
As far as looping through the array:
for (var i = 0; i<array.length; i++) {
var elem = array[i];
console.log(elem.name, elem.value);
}
// Outputs:
// parameter-name parameter-value2
// parameter-name2 parameter-value2
I'd store object literals in the array, like so:
var myArray = [];
myArray[0] = {name:"some name", value:"some value"};
myArray[1] = {name:"another name", value:"another value"};
for (i=0; i < myArray.length; i++) {
console.log(myArray[i].name + ' / ' + myArray[i].value);
}
// initialize empty array
var myArray = [];
// fill it with an object - the equivalent of a struct in javascript
myArray.push({
name: 'example-name'
value: 'example-value'
});
// repeat as neccessary
// walking through the array
for (var i = 0; i < myArray.length; i++)
{
// retrieving the record
record = myArray[i];
// and accessing a field
doSomething(record.name);
}
var array = {paramName: 'paramValue', paramName2: 'paramValue2'};
for(i in array) {
_tag.i = array.i;
}
There is no "Struct" in JavaScript only Object
my_array = new Array();
my_array.push({name: 'john', age:31});
my_array.push({name: 'da_didi', age:120});
for (i=0; i<my_array.length; i++)
{
alert(my_array[i].name);
}
How about
function Struct(name, value) {
this.name = name;
this.value = value;
}
arr[0] = new Struct("name1", "value1");
Javascript objects are loose objects: properties can be added and removed dynamically. So making a new Struct(), as you suggest, does -not- guarantee that the returned object will always have the properties you expect it to have. You have to check the availability of properties at the point of usage (duck typing):
var i, element;
for (i = 0; i < array.length; i++) {
element = array[i];
if (Object.hasOwnProperty.call(element, "name")
&& Object.hasOwnProperty.call(element, "value")) {
_tag[element.name] = element.value;
}
}
(Also, I'm just guessing that _tag is an object itself, but that wasn't clear from your example.)
You could probably use a more succinct syntax, but that depends heavily on the values of the properties. For example, you -might- be able to use something like this:
var i, element;
for (i = 0; i < array.length; i++) {
element = array[i];
if (element.name && element.value) {
_tag[element.name] = element.value;
}
}
But you need to realize that the above condition will be false not only if one or both of the properties (name and value) are undefined but also if the value of either or both refers to the empty string, null, 0, NaN, or false.