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]
Related
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);
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.
I have a text file in which I have data on every line. It looks like this:
number0;text0
number1;text1
number2;text2
..and so on
So I loaded that text file into a variable via xmlhttprequest and then I converted it into an array using split by "\n" so now the result of lineArray[0] is number0;text0.. And now what I need is to split that array again so I could use number0 and text0 separately.
My idea being that I want to get the text0 by searching number0 for example lineArray[i][1] gives me texti..
Any ideas how to proceed now?
Thanks
You need to do an additional split on ; as split(';') so that lineArray[0][1], lineArray[1][1] and so on gives you text0, text1 and so on.
var str = `number0;text0
number1;text1
number2;text2`;
var lineArray = str.split('\n').map(function(item){
return item.split(';');
});
console.log(lineArray);
console.log(lineArray[0][1]);
console.log(lineArray[1][1]);
Knowing I'm late, still making a contribution.
As everyone else said, split it again.
let text = "number0;text0\nnumber1;text1\nnumber2;text2"
let data = text.split('\n');
var objects = {};
for (var i = 0; i < data.length; i++) {
let key = data[i].split(';')[0]; // Left hand value [Key]
let value = data[i].split(';')[1]; // Right hand value [Value]
// Add key and value to object
objects[key] = value;
}
// Access by property
console.log(objects);
Using forEach
let text = "number0;text0\nnumber1;text1\nnumber2;text2"
let data = text.split('\n');
var objects = {};
data.forEach((elem) => {
let key = elem.split(';')[0]; // Left hand value [Key]
let value = elem.split(';')[1]; // Right hand value [Value]
objects[key] = value;
});
// Access by property
console.log(objects);
Just use split again with ";", like that:
myVar = text.split(';');
like #Teemu, #Weedoze and #Alex said
Convert the array into an object
Make an object out of it with another String split. To do so you can use the .reduce method to convert the array of strings into an object.
const strings = ['number0;text0', 'number1;text1', 'number3;text3', 'number4;text4'] ;
const obj = strings.reduce((acc,curr) => {
const [key, value] = curr.split(';');
acc[key] = value;
return acc;
}, {});
console.log(obj)
This way you can access text4 buy calling obj['number4'].
More about .reduce
The reduce method works by looping through strings
on each step acc is the accumulator: it contains the object that is getting filled with key/value pairs.
cur is the current item in the step
const [key, value] = curr.split(';') will to split the string into two strings and assign each to a seperate variable: key and value. It's called destructuring assignment
then I assign the key/value pair to the accumulator
the .reducemethod will return the accumulator on his state on the last step of the loop
Something like this could do the trick:
let a = "number0;text0\nnumber1;text1\nnumber2;text2";
let lines = a.split('\n');
let vals = [];
for(let line of lines) {
vals.push(line.split(';'))
}
console.log(vals); // Output
The last four lines create an empty array and split on the ';' and append that value to the vals array. I assume you already have the something like the first 2 lines
This question already has answers here:
Array.fill(Array) creates copies by references not by value [duplicate]
(3 answers)
Closed 4 years ago.
When i use Array.fill to fill a multidimensional array, i get a weird behaviour when pushing to one of the arrays:
var arr = Array(2).fill([]);
arr[0].push(5);
console.log(arr);
//=> prints [[5], [5]]
fill is essentially doing this:
var content = [];
for (var i = 0; i < 2; i += 1) {
arr[i] = content;
}
So, your array will have a reference to the array you've passed to fill in each property.
It sounds weird, but what your code actually does is create an array ([]) and put a reference for that array in each of the items of the Array(2). So whenever you change that reference - every array that is referenced to that Array is changed.
It's exactly the same as:
var a = [];
var arr = Array(2).fill(a);
a.push(5);
console.log(arr[0][0], arr[1][0]);
a[0] = 2;
console.log(arr[0][0], arr[1][0]);
You can see that the values inside the arr are affected by the change to the a array.
This question already has answers here:
Array.fill(Array) creates copies by references not by value [duplicate]
(3 answers)
Closed 4 years ago.
When i use Array.fill to fill a multidimensional array, i get a weird behaviour when pushing to one of the arrays:
var arr = Array(2).fill([]);
arr[0].push(5);
console.log(arr);
//=> prints [[5], [5]]
fill is essentially doing this:
var content = [];
for (var i = 0; i < 2; i += 1) {
arr[i] = content;
}
So, your array will have a reference to the array you've passed to fill in each property.
It sounds weird, but what your code actually does is create an array ([]) and put a reference for that array in each of the items of the Array(2). So whenever you change that reference - every array that is referenced to that Array is changed.
It's exactly the same as:
var a = [];
var arr = Array(2).fill(a);
a.push(5);
console.log(arr[0][0], arr[1][0]);
a[0] = 2;
console.log(arr[0][0], arr[1][0]);
You can see that the values inside the arr are affected by the change to the a array.