1

I am new to typescript. please help to push the data so here it goes Here the story goes I have string array and i need to push it to the json object

interface LocalIds {
    value: string;
    label: string;
  }

 const localIds = [
    { value: 'test', label: 'test' },
    { value: 'test2', label: 'test2' },
  ];


////////////// HERE in string array that data is coming ///////////
    const localIdentifiers: string[] = result.data.map((item: string) => item);


///////////// I want to push the string array data to json object with label & value////// 
// I experimented alot but giving some type error and all I am not getting 
    localIds.push({ label: 'abc', value: 'abc' });
 localIdentifiers.map(i => localIds.push(...localIds:{value:i,label:i}[])); //ERROR

1
  • Use JSON.stringify to convert an object to JSON Commented Nov 19, 2021 at 14:51

2 Answers 2

2

Half of your code does nothing useful

  • result.data.map((item: string) => item) will do nothing
  • using map when not returning anything inside it is pointless. At very least use forEach instead. or even better....

You should use map with concat:

interface LocalIds {
    value: string;
    label: string;
}

const localIds = [
    { value: 'test', label: 'test' },
    { value: 'test2', label: 'test2' },
];

localIds.push({ label: 'abc', value: 'abc' });
const finalLocalIds = localIds.concat( result.data.map((i: string) => ({value:i,label:i})) );

Live example

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

Comments

1

Try fixing last line as following

replace ; with , and remove [] at the end

localIdentifiers.map(i => localIds.push(...localIds, {value:i,label:i}));

also, you dont need ...localIds, since it will duplicate current array every time element is pushed to array

2 Comments

also you dont need a map!
forEach is better solution here

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.