简体   繁体   中英

Array values to a string in loop

I have an object (key value pair) looks like this

在此输入图像描述

I want to get a string of '[100000025]/[100000013]'

I can't use var str = OBJ[0].PC + OBJ[1].PC (which gives me '100000025100000013') because I need the bracket structure. The number of items can vary.

Added >> Can it be done without using arrow function?

 const string = array.map(({PC}) => `[${PC}]`).join('/')

您可以将每个字符串映射到括在括号中的字符串,然后通过斜杠将其连接起来。

You can use a map() and a join() to get that structure. - this is hte same solution as Puwka's = but without the template literal.

 var data = [ {am: 1, ct: "", pc: "1000000025"}, {am: 2, ct: "", pc: "1000000013"} ]; let newArr = data.map(item => "[" + item.pc +"]"); console.log(newArr.join("/")); // gives [1000000025]/[1000000013] 

You can always use classic for in loop

let arr = [{PC:'1000'},{PC:'10000'}]
let arrOut = [];
for(let i = 0; i < arr.length; i++) {
    arrOut.push('[' + arr[i].PC + ']'); 
}

now the arrOut is equal ["[1000]", "[10000]"] what we need is to convert it to a string and add '/' between items.

let str = arrOut.join('/');
console.log(str) // "[1000]/[10000]"

First if you want to divide the result then it will be better to change it into number and then just do the division. Example

Number.parseInt("100000025")/Number.parseInt("100000013")

If you want to display it then better to use string interpolation surround it with back tick [${[0].PC}]/[${[1].PC}]

Hope this is what are you looking for

So you need a string in the format of: xxxx/yyyyy from a complex object array.

const basedata = [...];
const result = basedata.map( item => `[${item.PC}]` ).join('/')

so i will explain it now. The map function will return a new array with 1 entry per item. I state that I want PC, but i added some flavor using ticks to inject it inbetween some brackets. At this point it looks like: ["[1000000025]","[100000013]"] and then join will join the arrays on a slash, so it will turn into an array.

"[100000025]/[100000013]"

Now, this will expand based on the items in your basedata. So if you have 3 items in your basedata array, it would return:

"[10000000025]/[100000013]/[10000888]"

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