Home > Enterprise >  Convert Array to object with duplicate keys
Convert Array to object with duplicate keys

Time:11-21

I want to convert the given array

arr = ['abc', 'def', 'hij'];

into this object:

result = {
'key': 'abc',
'key': 'def',
'key': 'hij'
}

----EDIT----

I want this structure because there is no way around other than this to pass this as queryParams in my project

CodePudding user response:

You can't create an object with duplicate keys, but you can create an array of individual objects:

const arr = ['abc', 'def', 'hij'];

const result = arr.map(str => Object.create({key: str}));
console.log(result);

CodePudding user response:

You can't have duplicated keys for object. But you can have array as value of an object key:

const arr = ['abc', 'def', 'hij'];
const obj = {};
obj.key = arr;

console.log(JSON.stringify(obj));

// output: {"key":["abc","def","hij"]}

CodePudding user response:

You are asking an XY Problem

The XY problem is asking about your attempted solution rather than your actual problem.

That is, you are trying to solve problem X, and you think solution Y would work, but instead of asking about X when you run into trouble, you ask about Y.

An object with duplicate keys is impossible in JavaScript.

You can use the URLSearchParams builtin to achieve your actual desired result:

const arr = ['abc', 'def', 'hij'];
const key = "key";

const urlSearchParams = new URLSearchParams();
for (const val of arr) {
  urlSearchParams.append(key, val);
}


console.log(urlSearchParams.toString());
console.log([...urlSearchParams.entries()]);

CodePudding user response:

To conveniently work with query parameters, use URLSearchParams. Don't try to give an object multiple values for one key; that's impossible.

let arr = ['abc', 'def', 'hij'];
const params = new URLSearchParams;
for (const x of arr) params.append('key', x);
console.log(params.toString());

  • Related