Dynamically assign properties to a JS object

非 Y 不嫁゛ 提交于 2020-01-23 11:03:11

问题


I needed to dynamically add properties to an js Object, which I achieved via eval():

$ ->

  #Methods
  window.add_address = (attributes, id=new Date().getTime())->
    $container = $('ul#addresses_list')
    $unit = $('<li>')

    $.each attributes, (key,value)->
      $input = $('<input type="hidden">')
      $input.attr 'name', "contact[addresses_attributes][#{id}][#{key}]"
      $input.val value
      $unit.append $input

    $container.append $unit

  #Events

  #Add address button
  $('a#add_address').on 'click', (ev)->
    attributes =  new Object
    $('#address_fields').find('input').each ->
      eval("attributes.#{$(this).attr 'id'}='#{$(this).val()}'");

    add_address attributes

This works perfect but I feel awkward with the eval(), is there anyway to do this "prettier"? I mean, I searched for alternatives like the Jquery .serializeArray() but it seems to work only with a queried form and I need to get the inputs from that #address_fields div.


回答1:


Use object['key'] notation

attributes[$(this).attr('id')] = $(this).val();

It's also very efficient to create object using:

var attributes={};

EDIT: Along similar lines can write the jquery methods in same notation

   attributes[$(this)['attr']('id')] = $(this)['val']();


来源:https://stackoverflow.com/questions/13115884/dynamically-assign-properties-to-a-js-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!