Javascript Object order incorrect [duplicate] - javascript

This question already has answers here:
How to keep an Javascript object/array ordered while also maintaining key lookups?
(2 answers)
Closed 7 years ago.
I have got a function which retrieves an object.
This object has a property and a value. The property is numeric and starts at "-30" all the way up to "50"
The problem is that when I loop through this object the browser seems to order it starting at "0" instead of starting at the initial property of "-30"
I need to make sure the order is exactly the same as the object.
var colorOj = {
"-30":"#111","-29":"#131313", ..etc.., "0":"#333", ..etc..,
"50":"#555"
}
function makeList(object){
for (var i in object) {
console.log(i); // Returns 0,1,2,3,4,5
// I need a return of -30,-29,-28,..., 0, 1, 2 ...
}
}
makeList(colorObj);

As suggested by #Teemu, properties are not stored in any specific order. But you can print them in any order using specific sort function accordingly.
Code
var obj = {};
for (var i = 5; i > -5; i--) {
obj[i * 10] = i * 10;
}
// Sort and get all keys...
var keys = Object.keys(obj).sort(function(a, b) {
return parseInt(a) - parseInt(b);
});
console.log(keys)
// Loop over keys to print values of each property
keys.forEach(function(item) {
console.log(item, obj[item]);
})

You can do something like this maybe:
var colorOj = {
"-30":"#111","-29":"#131313", "0":"#333",
"50":"#555"
};
var keys = Object.keys(colorOj).sort(function(a,b){return a - b})
for(var i = 0; i < keys.length;i++){console.log(keys[i])}
This way you can get every key in the object. Then sort it however you like(the sort function in javascript can take a compare function as a parameter look -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)

Related

How set up an JavaScript Array Object with a length of 5 to display empty strings on each key-value pair [duplicate]

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Is it possible to add dynamically named properties to JavaScript object?
(20 answers)
Closed 2 years ago.
I'm trying to find out how to initialise an array of objects, where each object has the index (i) as its key and 0 as its value. The code below is not working as expected but I can't see why. I'm still quite beginner with Javascript and couldn't find an answer elsewhere.
var n = 10;
var sample = [];
for (var i = 0; i < n; i++)
sample.push({i : 0});
you should use this syntax sample.push({[i]: 0});
when you need to access object property which is stored under some variable you should always use square brackets no matter you need write to or read from an object
The code below should take care of the job:
let n = 10;
let sample = Array.from({length:n}, (_, i) => ({ [i]: 0 }));
As pointed by Oleksandr Sakun on his answer, the index is used between brackets in order to evaluate the variable and set as a property of the object.
For a funcitonal approach you can try:
const initArray = (n)=>{
const newArr = new Array(n).fill(0);
return newArr.map((value, index)=> ({[index]: value}))
}
add square brackets to the index [i] :
var n = 10;
var sample = [];
for (var i = 0; i < n; i++)
sample.push({[i]: 0});
console.log(sample);

Make key value pair from two different array [duplicate]

This question already has answers here:
Merge keys array and values array into an object in JavaScript
(14 answers)
Closed 1 year ago.
I'm using local storage to get an arrays of strings,
First value attrIds is as follows,
var attrIds = localStorage.getItem('attributeids');
attrIds = JSON.parse(attrIds);
Second value confOptions is as follows,
I want something like this,
144: "5595"
93: "5487"
I have tried creating a loop inside the loop and tried to set the key and value but it's not working. I have also tried to set the single JSON object as key and setting value as '' but couldn't move further with that.
Does anyone have any idea regarding this?
You can accomplish this using a simple for loop, accessing the items from the arrays, and assigning properties to an empty object.
const keys = ['144', '93'];
const values = ['5595', '5487'];
const obj = {};
for (let i = 0; i < keys.length; i++) {
obj[keys[i]] = values[i];
}
console.log(obj); // prints { 144: '5595', 93: '5487' }
Create a nested array and then use Object.fromEntries().
const
a = ["144", "93"],
b = ["5595", "5487"],
c = Object.fromEntries(a.map((v, i) => [v, b[i]]));
console.log(c);
Using a for loop, you could do something like:
var attrIds = localStorage.getItem('attributeids');
attrIds = JSON.parse(attrIds);
confOptions = ["5595", "5487"]
const object = {};
for(let i=0; i<attrIds.length;i++)
object[attrIds[i]] = confOptions[i]

Javascript Grammer: how to assign correct values to an array of objects [duplicate]

This question already has answers here:
new Array(_).fill(object) does not create new instances of object [duplicate]
(5 answers)
Array.prototype.fill() with object passes reference and not new instance
(7 answers)
Closed 2 years ago.
let's look at the code:
Test() {
let array1 = new Array(5).fill({ a: 0 })
let array2 = new Array(5).fill({ a: 0 })
for (let i = 0; i < 5; i++) {
setTimeout(() => {
array1[i].a = i
array2[i] = {a:i}
console.warn("array = ", array1)
console.warn("array2 = ", array2)
}, 0.2 * i)
}
}
In this case, I wanna assign a series of values to the array1 & array2, and there are two ways to do it, which lead to totally different results.
In the case array1[i].a = i, after all the code is ran, the result is array = [{a:4},{a:4},{a:4},{a:4},{a:4}], which is not what i wanted.
In the second case array2[i] = {a:i}, the result will be [{a:0},{a:1},{a:2},{a:3},{a:4}] as expected.
I wanna know why is it like this? What's the machanics behind this phenomenon?
Thank you.
When you call .fill() and pass an object, you assign the exact same object to every element of the array. Thus, modifying a property at one array index modifies the same property at all the other indexes, because they're all pointing to the same thing.
There are a variety of ways around this issue. You could fill the array with 0 or null or some dummy value and then iterate through with .forEach(), or more simply just use an indexed for loop to initialize each element. If you initialize with { a: 0} in a for loop, a new object will be created on each iteration.

pick random value from associated array using javascript? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
JavaScript: Getting random value from an array
How can I choose an object key at random?
suppose we have an array like this:
var MrArray = new Array(5);
MrArray['one']='oneValue';
MrArray['two']='twoValue';
MrArray['three']='threeValue';
MrArray['four']='fourValue';
MrArray['five']='fiveValue';
ok?
the Array is associated.
and we have string key and string value.
now! how can i pick a random value from that?
Edit:i want to use like this:
Array Key Here
Regards
Sam
Using the method described here we can create the following function:
function randomKey(obj) {
var ret;
var c = 0;
for (var key in obj)
if (Math.random() < 1/++c)
ret = key;
return ret;
}
It returns a random key, so to get a random value from MrArray, do this:
var value = MrArray[randomKey(MrArray)];
jsPerf benchmark comparing the speed of this and the other answer.
Here:
function fetch_random(obj) {
var temp_key, keys = [];
for(temp_key in obj) {
if(obj.hasOwnProperty(temp_key)) {
keys.push(temp_key);
}
}
return obj[keys[Math.floor(Math.random() * keys.length)]];
}
Src: How can I choose an object key at random?

Checking length of dictionary object [duplicate]

This question already has answers here:
Length of a JavaScript object
(43 answers)
Closed 3 years ago.
I'm trying to check the length here. Tried count. Is there something I'm missing?
var dNames = {};
dNames = GetAllNames();
for (var i = 0, l = dName.length; i < l; i++)
{
alert("Name: " + dName[i].name);
}
dNames holds name/value pairs. I know that dNames has values in that object but it's still completely skipping over that and when I alert out even dName.length obviously that's not how to do this...so not sure. Looked it up on the web. Could not find anything on this.
What I do is use Object.keys() to return a list of all the keys and then get the length of that
Object.keys(dictionary).length
var c = {'a':'A', 'b':'B', 'c':'C'};
var count = 0;
for (var i in c) {
if (c.hasOwnProperty(i)) count++;
}
alert(count);
This question is confusing. A regular object, {} doesn't have a length property unless you're intending to make your own function constructor which generates custom objects which do have it ( in which case you didn't specify ).
Meaning, you have to get the "length" by a for..in statement on the object, since length is not set, and increment a counter.
I'm confused as to why you need the length. Are you manually setting 0 on the object, or are you relying on custom string keys? eg obj['foo'] = 'bar';. If the latter, again, why the need for length?
Edit #1: Why can't you just do this?
list = [ {name:'john'}, {name:'bob'} ];
Then iterate over list? The length is already set.
Count and show keys in a dictionary (run in console):
o=[];count=0; for (i in topicNames) { ++count; o.push(count+": "+ i) } o.join("\n")
Sample output:
"1: Phase-out Left-hand
2: Define All Top Level Taxonomies But Processes
3: 987
4: 16:00
5: Identify suppliers"
Simple count function:
function size_dict(d){c=0; for (i in d) ++c; return c}

Categories

Resources