-1

I have the following object called result of the form

0: "X"
1: "S"
2: "Z"
3: "C"
4: "W"
5: "X"
6: "M"
7: "A"
8: "D"
9: "V"
10: "M"
11: "F"
12: "I"
13: "H"

. How could I convert this object into a string of characters of the form XSZCWXMADVFIH ? I tried JSON.stringify (), but these functions return a response of the form

["X","S","Z","C","W","X","M","A","D","V","M","F","I","H"]
5
  • 3
    Use array.join('') to turn your array of items into a string without characters in between. Commented Jun 13, 2022 at 12:03
  • 2
    developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… + join Commented Jun 13, 2022 at 12:03
  • Does this answer your question? Convert a Char Array to a String Commented Jun 13, 2022 at 12:07
  • 1
    If JSON.stringify() returns [...], then the object you are referring to is an array. Commented Jun 13, 2022 at 12:07
  • 1
    Is it an object, or is that just the output of you logging an array in the console? Commented Jun 13, 2022 at 12:09

1 Answer 1

3

You can use Object.values to extract the object values into an array and then use the Array.prototype.join() method to join them by ''

const obj ={
0: "X",
1: "S",
2: "Z",
3: "C",
4: "W",
5: "X",
6: "M",
7: "A",
8: "D",
9: "V",
10: "M",
11: "F",
12: "I",
13: "H",
};

const str = Object.values(obj).join('');

console.log(str)

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

2 Comments

You're assuming it's an object from what the OP said but that data could also the output of an array logged in the console..
Also if you were to add 15: "J" this would add "J" to the 14th index and not the 15th index. (which might not matter for OPs output). This also might not work in environments that use engines that implement versions of the spec earlier than ES2020, as object property order for Object.values() wasn't specified back then (while most browser would iterate the keys in numeric order, it isn't guaranteed if they're pre ES2020). But all of this might not matter if OPs object is actually an array :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.