0

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

1
  • 4
    result.unshift(placeholder) Commented Jul 22, 2022 at 14:41

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

Comments

0

Obviously, Vue is a JavaScript's progressive framework so we can use the same functions of JavaScript here to merge the objects in Vue.

Please use the following feature on your code!

Object.assign(target, Obj1, Obj2, ...);

Albert

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.