Adding elements to object

前端 未结 17 2098
有刺的猬
有刺的猬 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:19
    function addValueInObject(object, key, value) {
        var res = {};
        var textObject = JSON.stringify(object);
        if (textObject === '{}') {
            res = JSON.parse('{"' + key + '":"' + value + '"}');
        } else {
            res = JSON.parse('{' + textObject.substring(1, textObject.length - 1) + ',"' + key + '":"' + value + '"}');
        }
        return res;
    }
    

    this code is worked.

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

    With that row

    var element = {};
    

    you define element to be a plain object. The native JavaScript object has no push() method. To add new items to a plain object use this syntax:

    element[ yourKey ] = yourValue;
    

    On the other hand you could define element as an array using

    var element = [];
    

    Then you can add elements using push().

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

    To append to an object use Object.assign

    var ElementList ={}
    
    function addElement (ElementList, element) {
        let newList = Object.assign(ElementList, element)
        return newList
    }
    console.log(ElementList)
    

    Output:

    {"element":{"id":10,"quantity":1},"element":{"id":11,"quantity":2}}

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

    Try this:

    var data = [{field:"Data",type:"date"},  {field:"Numero",type:"number"}];
    
    var columns = {};
    
    var index = 0;
    
    $.each(data, function() {
    
        columns[index] = {
            field : this.field,
            type : this.type
        };
    
        index++;
    });
    
    console.log(columns);
    
    0 讨论(0)
  • 2020-12-02 04:27

    Your element is not an array, however your cart needs to be an array in order to support many element objects. Code example:

    var element = {}, cart = [];
    element.id = id;
    element.quantity = quantity;
    cart.push(element);
    

    If you want cart to be an array of objects in the form { element: { id: 10, quantity: 1} } then perform:

    var element = {}, cart = [];
    element.id = id;
    element.quantity = quantity;
    cart.push({element: element});
    

    JSON.stringify() was mentioned as a concern in the comment:

    >> JSON.stringify([{a: 1}, {a: 2}]) 
          "[{"a":1},{"a":2}]" 
    
    0 讨论(0)
  • 2020-12-02 04:27

    push is an method of arrays , so for object you can get the index of last element ,and you can probably do the same job as push for object as below

    var lastIndex = Object.keys(element)[Object.keys(element).length-1];
    

    then add object to the new index of element

    element[parseInt(lastIndex) +1] = { id: id, quantity: quantity };
    
    0 讨论(0)
提交回复
热议问题