i am looping trough radio buttons to add their values to a javascript object. When i am doing a console.log i am seeing only the last item as an "part of a object" not the whole object.
What am I doing wrong?
var steps = {};
var elements = document.getElementsByTagName("input");
for(var i = 0; i<elements.length; i++) {
if(elements[i].type === "radio")
{
Object.assign(steps, {name: elements[i].value});
}
}
console.log(steps);
You are performing the following in a loop
Object.assign(steps, {name: elements[i].value});
what this basically does is add a key name with value elements[i].value.
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
You need to convert steps to an array and then push all of the keys in it. Alternatively you can change the name key and make it unique although converting it to array would be preferred.
For array you need to do something like this
var steps = [];
var elements = document.getElementsByTagName("input");
for (var i = 0; i < elements.length; i++) {
if (elements[i].type === "radio") {
steps.push({ name: elements[i].value });
}
}
console.log(steps);
I have three arrays filled with objects in JavaScript that I've put into a multi-dimensional array in order to get all possible combinations of all three objects to create a set of 'rules'. Then later in the code I want to be able to pull out the properties of these objects, but when I attempt to all I seem to be able to get is the string "[object]" and not the actual object itself.
This is how the array is put together:
var allArrays = [settings.serviceLevels, settings.serviceDays, settings.services];
function allPossibleCases(arr) {
if (arr.length === 1) {
return arr[0];
} else {
var result = [];
var allCasesOfRest = allPossibleCases(arr.slice(1));
for (var i = 0; i < allCasesOfRest.length; i++) {
for (var j = 0; j < arr[0].length; j++) {
result.push(arr[0][j] + allCasesOfRest[i]);
}
}
return result;
}
}
var uncheckedRules = allPossibleCases(allArrays);
I need to be able to get the properties out of settings.serviceLevels, settings.serviceDays and settings.services - I can find questions that do this with regular arrays but not with objects - is this even possible or have I taken it to a level where I've lost the properties?
Not sure I understood what you wanted. But here's a recursive function that will store in an array the properties of objects contained in another array :
function listProps(object, result) {
// for each property of the object :
for (objectProperty in object) {
// if it's an object, recursive call :
if (typeof object[objectProperty] === 'object') {
listProps(object[objectProperty], result);
} else { // otherwise, push it into the result array :
result.push(object[objectProperty]);
}
}
}
var allArrays = [settings.serviceLevels, settings.serviceDays, settings.services];
var result = [];
listProps(allArrays, result);
The result array should list every properties from the three objects settings.serviceLevels, settings.serviceDays, settings.services and their children (if they contain any object themselves).
Its hard to give this question a good name. I'll jump right into the example:
var people = [
{
john: {
score: 1
}
},
{
adam: {
score: 2
}
}
];
I need to loop through this array of objects and get the score values, the trick is I don't know the names (john, adam, ...) but I know each contains a score value.
How do I get them? My current code looks like this:
var pplArr = [];
for (i=0; i<people.length; i++) {
for (var key in people[i]) {
pplArr.push(key);
}
}
for (j=0; j<pplArr.length; j++) {
console.log(pplArr[j]);
//var nameVar = eval(pplArr[j]);
//console.log(people.[j].nameVar.score)
}
The commented section doesn't work since eval() returns undefined otherwise I think it would work. I also tried for (var key in people) and its variations with limited success. Also my two loops look like they are over-complicated, is there no simpler way?
I'm using AngularJS (ionic) thus I would prefer not to use jQuery.
You can use map() and Object.keys().map() will help to iterate over array and Object.keys() helps to gets object keys as an array, get first one from array and get the value.
var people = [{
john: {
score: 1
}
}, {
adam: {
score: 2
}
}];
var res = people.map(function(v) {
return v[Object.keys(v)[0]].score;
});
console.log(res);
Since you don't know if you have more than one person in each object you can recourse in the object looking for all properties named score and return the values in an array like this:
function getAllProperties(o, p){
var properties = [];
Object.keys(o).forEach(function (k) {
if (typeof o[k] === "object") {
properties = properties.concat(getAllProperties(o[k], p));
} else if (k === p) {
properties.push(o[k]);
}
});
return properties;
}
console.log(getAllProperties(people, "score"));
If you want the score of each object in people array, you could do something like this:
for (var i = 0; i < people.length; i++) {
var person = people[i];
for (var key in person) {
for (score in person[key]) {
console.log(person[key][score])
}
}
}
I have seen many posts about searching nested arrays in javascript but none of them have a way to tell if an item does not exist in the array.
this may sound confusing so here are some examples:
I have 2 arrays oldArray and newArray
structured like this:
array(
[0]=>array([name]:"name"
[location]:"location")
[1]=>array([name]:"name2"
[location]:"location2")
)
both arrays are structured this way.
I need to be able to know which names exist in the old array and not in the new and vice versa.
here is what I have tried:
var name= oldArray[key]['name'];
for (var key in oldArray) {
for(var i= 0, len = newArray.length; i < len; i++){
if(newArray[i]['name'] == name){
//push to array
}
else{
//push to different array
}
}
}
this way I will have an array that contains all names that exist in both arrays and an array that only contains names that exist in the oldArray..
this doesn't seem to work because it is a 1 to 1 comparison. the first array is correct but the array that should only contain the names that exist in the old array is not correct.
Use a boolean to keep track of whether there is a match in the new array. Then after you complete the inner for loop over the newArray, check boolean to see if no matches were found, then push to other array.
var name= oldArray[key]['name'];
for (var key in oldArray)
{
var foundMatch=false
for(var i= 0, len = newArray.length; i < len; i++)
{
if(newArray[i]['name'] == name)
{
//push to array
foundMatch=true;
break;
}
}
if(foundMatch==false)
//push to different array
}
Have you initialized the array for old values?
Are you getting an exception?
Have you debugged it with Chrome?
edit:
I think if you do:
for all old values push if exists and ask again and push, it will keep pushing in an infinite loop.
try to add a break
var name= oldArray[key]['name'];
for (var key in oldArray) {
for(var i= 0, len = newArray.length; i < len; i++){
if(newArray[i]['name'] == name){
//push to array
break;
}
else{
if(i==newArray.length-1)
//push to different array
}
}
}
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.