-2

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);

Screenshot1

Second value confOptions is as follows,

Screenshot2

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?

Mohit Rane
  • 149
  • 1
  • 1
  • 11
  • You want to map each value from the first array with every value of the second array from the same index? – Alexandru Corlan Apr 19 '21 at 16:11
  • yes as i mentioned in my question – Mohit Rane Apr 19 '21 at 16:12
  • 1
    [There's no such thing as a "JSON Object"](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/). `.getItem()` returns a string. `attrIds` and `confOptions` are both arrays of strings. – Andreas Apr 19 '21 at 16:13

3 Answers3

2

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);
Som Shekhar Mukherjee
  • 4,701
  • 1
  • 12
  • 28
1

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]
Vasi Maruseac
  • 66
  • 1
  • 1
  • 8
1

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' }
Johann
  • 187
  • 1
  • 4
  • 11