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"}];
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"}];
Share
Improve this question
edited Apr 16, 2019 at 10:35
jo_va
14k3 gold badges25 silver badges49 bronze badges
asked Apr 16, 2019 at 7:24
minnu merin alexminnu merin alex
971 gold badge2 silver badges9 bronze badges
3
- 1 what you actually want to do?? – Syed Kashif 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 ? – jo_va Commented Apr 16, 2019 at 10:36
- 1 id's should be unique, why are you keeping same id for every object ? – Code Maniac Commented Apr 16, 2019 at 10:39
2 Answers
Reset to default 3Use 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);
let selectedIds = Input.map(item =>
{
return {
id: item.text,
name: item.id
};
})