1

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

7
  • 4
    That’s not possible. 1 property per name Commented Nov 20, 2022 at 23:53
  • 3
    why would you do that? what are you trying to do? Commented Nov 20, 2022 at 23:54
  • see stackoverflow.com/questions/66444257/… Commented Nov 21, 2022 at 0:09
  • 1
    object keys must be unique, I mean... did you think of how do you even access the values if you have duplicated keys? Commented Nov 21, 2022 at 2:13
  • @Georgemff I want to pass this into queryParams in URL Commented Nov 21, 2022 at 2:47

4 Answers 4

4

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

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

1 Comment

The output is in Array, I want output in Object.
2

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"]}

2 Comments

This is wrong output, I want like this: { 'key': 'abc', 'key': 'def', 'key': 'hij' }
you can't do that, object doesn't work that way.
1

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

1 Comment

I believe this answers the question. An excerpt from the question: I want this structure because there is no way around other than this to pass this as queryParams in my project
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.