简体   繁体   中英

how do i add all js array objects to one string?

I want to use a JSON and add all of the IDs into a string, but I am having some trouble. I am fairly new to working with JSON objects, so please explain how it works if you have any ideas.

I want to convert this:

let users = [
  {"id":"24317318904217xxxx","name":"person 1"},
  {"id":"69336408842371xxxx","name":"person 2"}
]

var str = `ID\'s `

To something like this:

`ID's: <@24317318904217xxxx>, <@69336408842371xxxx>`

Thanks in advance!

You can use map() method in javascript to create this structure.

Basically, you create a string with use template string then push it inside your array variable and modify it.

1 - Create an array with use your data

str = users.map(user => `@${user.id}`)

2 - Add 'ID's' text into your variable and use join() method to convert your data as a string

str = `ID\s ${str.join(', ')}`

Have a nice and productive day!

Full Code:

 let users = [{ "id": "24317318904217xxxx", "name": "person 1" }, { "id": "69336408842371xxxx", "name": "person 2" } ] str = users.map(user => `<@${user.id}>`) str = `ID\s ${str.join(', ')}` console.log(str)

When you are new to JS, you can get started with a simple for loop over the users array like this:

let users = [
  {"id":"24317318904217xxxx","name":"person 1"},
  {"id":"69336408842371xxxx","name":"person 2"}
]

let str = "ID's: ";

for (let i = 0; i < users.length; i++) {
    str += `<@${users[i].id}>`;
    if (i < users.length - 1)
        str += ", ";
}

To access the i-th object in the array (0-indexed) use users[i] ;

To access an object's 'id' property simply use object.id . Same with name and all other properties.

Read more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object

The string concatenation might look a bit weird to you, it's a string template see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String

The other answer uses map and join which you can read more about on the array mdn article. I highly recommend you reading into it, as Javascript code often uses these functions, but might need so getting used to for people who only ever written iterative code.

If you have any other questions feel free to ask in the comments!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM