2

I am new to Typescript. I want to select ids from observable I have an array as below. Please help me to get the expected output.

const Input=[{
  "id": 1,
  "text": "My Choice 1"
}, {
  "id": 2,
  "text": "My Choice 2"
}, {
  "id": 3,
  "text": "My Choice 3"
}, {
  "id": 4,
  "text": "My Choice 4"
}, {
  "id": 5,
  "text": "My Choice 5"
}];

Expected Result :

let selectedIds = [
      {id: "Choice", name: "2"},
      {id: "Choice", name: "3"},
      {id: "Choice", name: "5"}];
3
  • 1
    what you actually want to do?? Commented Apr 16, 2019 at 7:27
  • Could you explain the relation between your Input and Output ? Are you filtering ? based on what criteria ? How do you transform your Input ? Commented Apr 16, 2019 at 10:36
  • 1
    id's should be unique, why are you keeping same id for every object ? Commented Apr 16, 2019 at 10:39

2 Answers 2

3

Use array.map to transform the objects

 const Input=[{
  "id": 1,
  "text": "My Choice 1"
}, {
  "id": 2,
  "text": "My Choice 2"
}, {
  "id": 3,
  "text": "My Choice 3"
}, {
  "id": 4,
  "text": "My Choice 4"
}, {
  "id": 5,
  "text": "My Choice 5"
}];

let Result = Input.map(choice => ({ id: "choice", name: choice.id }));
console.log(Result);

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

2 Comments

I want to send this result as a string to pass it as a variable in a query. let res = this.apollo.use('dataInsert').mutate({ mutation: researchCreate, variables: { result: Result } }); where "result" accepts string.How will i pass the avove Result as string.
Use const myString = Json.stringify(Result);. Json.stringify(jsonData) converts Json data to a string and returns it
2
let selectedIds = Input.map(item => 
{
  return {
    id: item.text,
    name: item.id
  };
})

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.