如何添加到JSON obj

时间:2018-03-16 03:53:32

标签: javascript json

如果我有这样的对象

const myobj ={
"Computer" : [{ "file" : MyDirectory/A/text1.txt", "line": [23,56]},
{"file" :"MyDirectory/B/text5.txt", "line" :[32,91]}] ,
 "Book" : {"file": MyDirectory/A/text1.txt", "line": [13,46]} 
}

并假设一个函数产生类似

的东西
{"Computer" : [{ "file" : MyDirectory/A/text1.txt", "line": [3,6]} 

有没有办法可以将它连接到与“myobj”中的“computer”键对应的列表?我可以将我的obj更新为{     “计算机”:[{“file”:MyDirectory / A / text1.txt“,”line“:[23,56]},     {“file”:“MyDirectory / B / text5.txt”,“line”:[32,91]},{“file”:MyDirectory / A / text1.txt“,”line“:[3,6]} ],      “预订”:{“file”:MyDirectory / A / text1.txt“,”line“:[13,46]}     }?

2 个答案:

答案 0 :(得分:0)

//让"某事"是你提到的json:
var something = {" Computer" :[{" file" :MyDirectory / A / text1.txt"," line":[3,6]}]};

//将它们添加到myobj:
something.Computer.forEach(函数(t)的{myobj.Computer.push(T)})

答案 1 :(得分:0)



const myobj ={"Computer" : [{ "file" : "MyDirectory/A/text1.txt", "line": [23,56]},
{"file" :"MyDirectory/B/text5.txt", "line" :[32,91]}] ,
 "Book" : {"file": "MyDirectory/A/text1.txt", "line": [13,46]} 
}

var newObj = {"Computer" : [{ "file" : "MyDirectory/A/text1.txt", "line": [3,6]}]} 

for (var i in myobj) {
   for (j in newObj) {
   if (i === j) {
       myobj[i] = myobj[i].concat(newObj[i]);
   }
   }
}

console.log(myobj);