Adding elements to object

前端 未结 17 2099
有刺的猬
有刺的猬 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:32

    Adding new key/pair elements into the original object:

    const obj = { a:1, b:2 }
    const add = { c:3, d:4, e: ['x','y','z'] }
    
    Object.entries(add).forEach(([key,value]) => { obj[key] = value })
    

    obj new value:

    {a: 1, b: 2, c: 3, d: 4, e: ["x", "y", "z"] }
    
    0 讨论(0)
  • 2020-12-02 04:33

    if you not design to do loop with in JS e.g. pass to PHP to do loop for you

    let decision = {}
    decision[code+'#'+row] = event.target.value
    

    this concept may help a bit

    0 讨论(0)
  • 2020-12-02 04:34

    If the cart has to be stored as an object and not array (Although I would recommend storing as an []) you can always change the structure to use the ID as the key:

    var element = { quantity: quantity };
    cart[id] = element;
    

    This allows you to add multiple items to the cart like so:

    cart["1"] = { quantity: 5};
    cart["2"] = { quantity: 10};
    
    // Cart is now:
    // { "1": { quantity: 5 }, "2": { quantity: 10 } }
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-02 04:34

    you should write var element = [];
    in javascript {} is an empty object and [] is an empty array.

    0 讨论(0)
  • 2020-12-02 04:34

    This is an old question, anyway today the best practice is by using Object.defineProperty

    const object1 = {};
    
    Object.defineProperty(object1, 'property1', {
      value: 42,
      writable: false
    });
    
    object1.property1 = 77;
    // throws an error in strict mode
    
    console.log(object1.property1);
    // expected output: 42
    
    0 讨论(0)
提交回复
热议问题