Home > front end >  How to merge a object to a array object in vuejs
How to merge a object to a array object in vuejs

Time:07-23

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

CodePudding user response:

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)

CodePudding user response:

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

  • Related