Adding elements to object

前端 未结 17 2163
有刺的猬
有刺的猬 2020-12-02 04:11

I need to populate a json file, now I have something like this:

{\"element\":{\"id\":10,\"quantity\":1}}

And I need to add another \"elemen

17条回答
  •  [愿得一人]
    2020-12-02 04:34

    I was reading something related to this try if it is useful.

    1.Define a push function inside a object.

    let obj={push:function push(element){ [].push.call(this,element)}};
    

    Now you can push elements like an array

    obj.push(1)
    obj.push({a:1})
    obj.push([1,2,3])
    

    This will produce this object

    obj={
     0: 1
     1: {a: 1}
     2: (3) [1, 2, 3]
     length: 3
    }
    

    Notice the elements are added with indexes and also see that there is a new length property added to the object.This will be useful to find the length of the object too.This works because of the generic nature of push() function

提交回复
热议问题