根据键更新或创建数组中的对象

时间:2017-06-18 02:48:31

标签: javascript arrays object

嗨,这是我的对象数组:

notes:Array(3)
0:Object
1497752995725:
"{"id":"1497752995725","top":"470.047px","left":"1130px","text":""}"

1:Object
1497753006544:"{"id":"1497753006544","top":"470.047px","left":"1130px","text":"dadssad"}"

2:Object
1497753006544:
"{"id":"1497753006544","top":"325.047px","left":"585px","text":"dadssad"}"

和我使用的代码:

var notes = []
var obj = {
      id: sticky.attr('id'),
      top: sticky.css('top'),
      left: sticky.css('left'),
      text: sticky.children('.sticky-content').html()
      }

var item = {}
item[obj.id] = JSON.stringify(obj)
notes.push(item)

我想要这种类型的输出:

notes:Array(3)
1497752995725:
"{"id":"1497752995725","top":"470.047px","left":"1130px","text":""}"
1497753006544:
"{"id":"1497753006544","top":"470.047px","left":"1130px","text":"dadssad"}"
1497753006544:
"{"id":"1497753006544","top":"325.047px","left":"585px","text":"dadssad"}"

音符可以是数组或对象,所以当键例如。 1497752995725存在密钥的对象值,当没有密钥1497752995725将与新主体一起创建时将更新。

1 个答案:

答案 0 :(得分:0)

只需将笔记作为对象

var notes = {}

var obj = {
  id: sticky.attr('id'),
  top: sticky.css('top'),
  left: sticky.css('left'),
  text: sticky.children('.sticky-content').html()
}
notes[obj.id] = obj

它会更新相同密钥的数据。