I have an object something below in the code. but while iterating over the object i get only the last value. I cannot understand what i am doing wrong here !
var index = {};
var demoObj = [{
0:{obj1: {...}, obj2: {...}, obj3: {...}}
},
{
1:{obj1: {...}, obj2: {...}, obj3: {...}}
}];
for (var i = 1; i <= demoObj.length; ++i) {
index[i] = demoObj[i] ;
}
console.log(index);
Seems like you are skipping index 0
for (var i = 1; i <= demoObj.length; ++i) {
change to this
for (var i = 0; i <= demoObj.length; ++i) {
You are logging your value after the for loop is done, try logging it inside the for loop.
And also variables are lowercase ;)
for (var i = 1; i <= demoObj.length; ++i) {
index[ i ] = demoObj[i] ;
console.log(Index);
}
Related
I wanted to create a function, that counts all unique Items in an array, but somehow I do not get any output.
This is my array!
let arr = ["hi", "hello", "hi"];
And this is the code I wrote so far:
function countUnique(arr) {
var counts = {};
for (var i = 0; i < arr.length; i++) {
counts[arr[i]] = 1 + (counts[arr[i]] || 0);
}
countUnique(arr);
}
console.log(countUnique(arr));
Your are counting values correctly, however then you are calling this method recursively countUnique(arr); and it results an error of call stack exceeded.
So just remove recursive call of method countUnique(arr); and return counted value counts:
function countUnique(arr) {
var counts = {};
for (var i = 0; i < arr.length; i++) {
counts[arr[i]] = 1 + (counts[arr[i]] || 0);
}
return counts;
}
let arr = ["hi", "hello", "hi"];
console.log(countUnique(arr));
JavaScript engine limits the maximal recursion depth. We can rely on it being 10000, some engines allow more.
You could take a Set and return the size.
const countUnique = array => new Set(array).size;
console.log(countUnique(["hi", "hello", "hi"]));
let arr = ["hi", "hello", "hi"];
function countUnique(arr) {
var counts = {};
for (var i = 0; i < arr.length; i++) {
if(arr[i] in counts) {
counts[arr[i]]++;
} else {
counts[arr[i]] = 1;
}
}
return Object.keys(counts).length;
}
console.log(countUnique(arr));
I'm trying add items in object in for loop , but last item always rewrites values that I added before.
P/S I've posted similar question before but code was too complicated , I made sample to explain my problem .
here is in jsfiddle: https://jsfiddle.net/armakarma/ykwc3xse/8/
test(){
let array = [4,6,7,1]
let object={}
for (let i = 0; i < array.length; i++){
object[array[i]]={name: 'test', id:30}
if(array[i] > 7){
object[array[i]]={render: true}
} else{
object[array[i]]={render: false}
}
}
console.log(object)
}
In your if/else statements you are overwriting the object keys. Instead you should use spread operator to add properties to existing keys like this:
function test() {
let array = [4, 6, 7, 1];
let object = {};
for (let i = 0; i < array.length; i++) {
object[array[i]] = { name: 'test', id: 30 };
if (array[i] > 7) {
object[array[i]] = { ...object[array[i]], render: true };
} else {
object[array[i]] = { ...object[array[i]], render: false };
}
}
console.log(object);
}
test()
You should use >= instead of >, the result you are trying to achieve is never going to be since the condition you are checking is wrong:
array = [4,6,7,1]
object={}
for (let i = 0; i < array.length; i++) {
object[array[i]] = { name: "test", id: 30 };
if (array[i] >= 7) {
object[array[i]].render = true;
} else {
object[array[i]].render = false;
}
}
console.log(object)
Another way, to do what you want is to use a reduce function :
test() {
let array = [4, 6, 7, 1]
const object = array.reduce((acc, value) => {
return { ...acc, [value]: { name: 'test', age: 30, render: value <= 7 } }
}, {})
console.log(object)
}
It's cleaner than use a for loop.
In your example, you are adding an attribute/property/key which is object[array[i]] and will be the same for that loop.
So definitely the if--else block will replace the value with the same key
You can do as follows :
function test() {
let array = [4,6,7,10]
let object={};
for (let i = 0; i < array.length; i++){
let myobj={name: 'test', id:30};
if(array[i] > 7){
myobj.render= true;
} else{
myobj.render= false;
}
object[array[i]] =myobj;
}
console.log(object);
}
test()
I'd like to use an object to configure some settings for an app. My idea is to start with this:
var obj = {
property_one: 3;
property_two: 2;
property_three: 1;
}
And I would like to end up with this:
var array = [
'property_one','property_one','property_one',
'property_two','property_two',
'property_three'
]
My current solution is to do this for each property:
function theConstructor(){
for(i=1; i <= obj.property_one; i++){
this.array.push('property_one');
};
for(i=1; i <= obj.property_two; i++){
this.array.push('property_two');
};
for(i=1; i <= obj.property_two; i++){
this.array.push('property_two');
};
}
But this gets tedious, because I might have many properties, and these might change as the app evolves.
I know I can loop through object's properties like this:
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
array.push(key);
}
}
But this will push the value to the array, not the key (as a string). Any ideas about how I can do this more efficiently?
Try this
function theConstructor(){
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
for(var i=1; i <= obj[key]; i++){
this.array.push(key);
};
}
}
}
Using Array.prototype.reduce():
var obj = {
property_one: 3,
property_two: 2,
property_three: 1
};
var resultArray = Object.keys(obj).reduce(function(result, curItem) {
for (var index = 0; index < obj[curItem]; index++) {
result.push(curItem);
}
return result;
}, []);
document.write(JSON.stringify(resultArray));
I was writing to see if I can manipulate jquery arrays.
So I have an object:
myobject = {
abc : {
value : 'abc',
template : '<div class="abc"></div>',
},
},
Now what I have is another array that looks like this:
myarray = ["abc", "cde"];
So what I am trying to do is loop through myarray to see if it matches an object in the myobject.
Now I thought you would accomplish this by doing something like this:
for (var i = 0; i < myarray.length; i++) {
if (myobject.myarray[i]) {
// do something
}
}
Now this gives me an error: Uncaught TypeError: Cannot read property '0' of undefined
So clearly this isn't the approach, how can I loop through myarray to see if myobject has an object that matches the name from the myarray array?
The problem within your code is, that myobject.myarray does not exists, so 0 of a non object is not available. Try to check with in:
for (var i = 0; i < myarray.length; i++) {
if (myarray[i] in myobject) {
// do something
}
}
You can treat a javascript object la dictionary.
Documentation
myobject = {
abc: {
value: 'abc',
template: '<div class="abc"></div>',
},
},
myarray = ["abc", "cde"];
for (var i = 0; i < myarray.length; i++) {
console.log(myobject[myarray[i]]);
}
You need to change the object reference from myobject.myarray[i] to myobject[myarray[i]]
var myobject = {
'abc' : {
value : 'abc',
template : '<div class="abc"></div>',
}
};
var myarray = ["abc", "cde"];
for (var i = 0; i < myarray.length; i++) {
if (myobject[myarray[i]]!=undefined) {
console.log(myobject[myarray[i]]);
}
}
You should be able to do the following.
for (var i = 0; i < myarray.length; i++) {
if (myobject.hasOwnProperty(myarray[i])) {
// do something
}
}
You were close with iterating through the array to look for the match, to finish use hasOwnProperty to check if the current place in the array matches any property in myobject
var myobject = {
abc: {
"value": "abc",
"template": "test"
}
}
var myarray = [ "abc", "cde" ];
for (var i = 0; i < myarray.length; i++) {
var thisKey = myarray[i];
if (myobject.hasOwnProperty(thisKey)) {
//match found
}
}
http://jsfiddle.net/jessikwa/obpacbao/3/
I have the below javascript array with me
var test =[{
Maths:{
ST1:10,
ST2:2,
ST3:15}
},
{
Science:{
ST1:50,
ST3:40}
}
]
I want to generate the array shown below out of this
var t = [{ST1:{
Maths:10,
Science:50
},
ST2:{
Maths:2,
Science:0
},
ST3:{
Maths:15,
Science:40
}
}]
I tried using the code shown below
for (var key in test) {
if (test.hasOwnProperty(key)) {
for (var key1 in test[key]){
//console.log(key1)}
var abc = test[key][key1];
for(var x in abc)
{
console.log(x+key1+abc[x])
}
}
}
}
I am new to this help me doing this.
This does mostly what you want...
var t = {};
for (var i = 0; i < test.length; i++) {
for (var name in test[i]) {
for (var level in test[i][name]) {
if (!t[level])
t[level] = {}
t[level][name] = test[i][name][level]
}
}
}
Only thing missing is to get the Science:0 for when a STx value is missing under a section.
DEMO: http://jsfiddle.net/eHwBC/
Result:
{
"ST1": {
"Maths": 10,
"Science": 50
},
"ST2": {
"Maths": 2
},
"ST3": {
"Maths": 15,
"Science": 40
}
}
Keep in mind that there's no guaranteed order when using for-in for enumeration.
If the labels (Math, Science, etc) are known in advance, then you can ensure that each object gets all labels.
If not, a separate loop can be done. Depending on the approach, it could be done before or after this main loop.
Do you know about JSON.stringify(t)?
It will convert an object literal to JSON.
Mozilla's documentation of this function is available at https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/stringify.
You can also read this blog article for further explanation
Try this:
var test =[{
Maths:{
ST1:10,
ST2:2,
ST3:15
}
},
{
Science:{
ST1:50,
ST3:40}
}
];
var result = [];
for(i = 0; i <= test.length; i++){
var resultRow = {};
for(key in test[i]){
for(subKey in test[i][key]){
if(resultRow[subKey] == undefined){
resultRow[subKey] = {};
}
resultRow[subKey][key] = test[i][key][subKey];
}
}
result.push(resultRow);
}
Try like below,
/* Iterator start */
var t = {};
for (var i = 0; i < test.length; i++) { //Iterate Maths, Science,..
for (var key in test[i]) { //Iterate Math
for (var iKey in test[i][key]) { //Iterate ST1, ST2, ST3
var s = (t.hasOwnProperty(iKey))?t[iKey]:createObject();
s[key] = test[i][key][iKey];
t[iKey] = s;
}
}
}
/* Iterator End */
p = [];
p.push(t);
//^- p is what you want
// Separate function so you can add more items later without changing logic
function createObject () {
return {'Maths' : 0, 'Science': 0};
}
DEMO and Proof below,