Home > front end >  how to format string data like this '[1,fish#, 15,bird#, 4,horse#]' to '1,fish#15,bir
how to format string data like this '[1,fish#, 15,bird#, 4,horse#]' to '1,fish#15,bir

Time:10-20

how to format string data like this '[1,fish#, 15,bird#, 4,horse#]' 

to '1,fish#15,bird#4,horse#'

CodePudding user response:

You need to create the model and map the list to the model

In your case your model class looks like this

class User  {
  final int user;
  final String tag;
  User({ required this.user, required this.tag, 
  
  });
}

List like this

 final List<User> userlist = [User(user: 4, tag: "ahmed#"),User(user: 15, tag: "up#"),];

when you need to get data use like this

userlist[0].tag,//0 is index

example

print(userlist[0].tag,) //this will print  **ahmed#**

CodePudding user response:

Simply using join and replaceAll.

export default function App() {
  const encode = (source: string[]): string => {
    return source.join(",").replaceAll("#,", "#");
  };

  const decode = (source: string): string[] => {
    return source
      .split(",")
      .reduce((p, n) => [...p, ...n.split("#")], new Array<string>())
      .map((e, i) => (i % 2 === 0 ? e : `${e}#`))
      .filter((e) => !!e);
  };

  let source = ["1", "fish#", "15", "bird#", "4", "horse#"];

  let sourceEncoded = encode(source);
  console.log("encode", sourceEncoded);
  // -> 1,fish#15,bird#4,horse# 

  let sourceDecoded = decode(sourceEncoded);
  console.log("decode", sourceDecoded);
  // -> ["1", "fish#", "15", "bird#", "4", "horse#"]

  return (
    <div className="App">
      ...
    </div>
  );
}


Code sanbox sample (console).

Edit fervent-volhard-mwc585

  • Related