I have a api response.data
[{id: 1, name:"Test 1"},{id: 2, name:"Test 2"}]
And my component .vue
... created() { const request = axios.get("***api_url***").then(response => { const result = response.data; const placeholder = { 'id': 0, 'name': '[Select]' }; const newObject = result.concat( placeholder.map( item => ({id: item.id, name: item.name}) ) ); console.log(newObject); }); }
I want merge placeholder object to result after api response
Advertisement
Answer
Result is actually a list. You can use the destructuring assignment
const result = [{id: 1, name:"Test 1"},{id: 2, name:"Test 2"}]; const placeholder = {id:0, name: "[Select]"}; const newObject = [ placeholder, ...result ];
to prepend the placeholder.
To use concat you must wrap the placeholder in a list.
[placeholder].concat(result)
to achieve the same result in a “more conservative way”.
Or you can use the Object.unshift
as suggested by @kemicofa ghost.
result.unshift(placeholder)