-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?

3
  • You want to map each value from the first array with every value of the second array from the same index? Commented Apr 19, 2021 at 16:11
  • yes as i mentioned in my question Commented Apr 19, 2021 at 16:12
  • 1
    There's no such thing as a "JSON Object". .getItem() returns a string. attrIds and confOptions are both arrays of strings. Commented Apr 19, 2021 at 16:13

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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' }

Comments

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]

1 Comment

please add a full solution with for loop, really appreciated

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.