Home > Net >  How to push string array to json object?
How to push string array to json object?

Time:11-20

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

I don't know why you are using ...localIds, if you want to push an item to your object just try this:

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

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

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

const data = ["Saab", "Volvo", "BMW"]; //dummy data
const localIdentifiers: string[] = data;

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

 console.log(localIds);

Check the example here

  • Related