경고와 경고에 대한 정보를 보유한 개체가 있습니다.
var alerts = {
1: { app: 'helloworld', message: 'message' },
2: { app: 'helloagain', message: 'another message' }
}
이 외에도 몇 개의 경고가 있는지 알려주는 변수가 있습니다 alertNo
. 내 질문은 새 경고를 추가 할 때 경고를 alerts
객체 에 추가하는 방법이 있습니까?
답변
경고를 단일 객체의 속성 대신 배열에 레코드로 저장하는 것은 어떻습니까?
var alerts = [
{num : 1, app:'helloworld',message:'message'},
{num : 2, app:'helloagain',message:'another message'}
]
그리고 하나를 추가하려면 다음을 사용하십시오 push
.
alerts.push({num : 3, app:'helloagain_again',message:'yet another message'});
답변
jQuery $.extend(obj1, obj2)
는 2 개의 객체를 병합하지만 실제로 배열을 사용해야합니다.
var alertsObj = {
1: {app:'helloworld','message'},
2: {app:'helloagain',message:'another message'}
};
var alertArr = [
{app:'helloworld','message'},
{app:'helloagain',message:'another message'}
];
var newAlert = {app:'new',message:'message'};
$.extend(alertsObj, newAlert);
alertArr.push(newAlert);
답변
Object.assign () 으로이 작업을 수행 할 수 있습니다 . 때로는 배열이 필요하지만 OData 호출과 같은 단일 JSON 객체가 필요한 함수로 작업 할 때이 방법을 풀기 위해 배열을 만드는 것보다 간단합니다.
var alerts = {
1: {app:'helloworld',message:'message'},
2: {app:'helloagain',message:'another message'}
}
alerts = Object.assign({3: {app:'helloagain_again',message:'yet another message'}}, alerts)
//Result:
console.log(alerts)
{
1: {app:'helloworld',message:'message'},
2: {app:'helloagain',message:'another message'}
3: {app: "helloagain_again",message: "yet another message"}
}
편집 : 다음 키를 얻는 것과 관련된 의견을 해결하기 위해 Object.keys () 함수 를 사용하여 키 배열을 얻을 수 있습니다 . 키를 증가시키는 예는 Vadi의 답변을 참조하십시오. 마찬가지로 Object.values () 및 Key-values 쌍을 사용하여 Object.entries ()를 사용 하여 모든 값을 가져올 수 있습니다 .
var alerts = {
1: {app:'helloworld',message:'message'},
2: {app:'helloagain',message:'another message'}
}
console.log(Object.keys(alerts))
// Output
Array [ "1", "2" ]
답변
다른 답변에서 지적했듯이 배열을 사용하는 것이 더 쉽다는 것을 알 수 있습니다.
그렇지 않은 경우 :
var alerts = {
1: {app:'helloworld',message:'message'},
2: {app:'helloagain',message:'another message'}
}
// Get the current size of the object
size = Object.keys(alerts).length
//add a new alert
alerts[size + 1] = {app:'Your new app', message:'your new message'}
//Result:
console.log(alerts)
{
1: {app:'helloworld',message:'message'},
2: {app:'helloagain',message:'another message'}
3: {app: "Another hello",message: "Another message"}
}
시도 해봐:
https://jsbin.com/yogimo/edit?js,console
답변
다음과 같이 스프레드 구문을 사용할 수 있습니다.
var alerts = {
1: { app: 'helloworld', message: 'message' },
2: { app: 'helloagain', message: 'another message' }
}
alerts = {...alerts, 3: {app: 'hey there', message: 'another message'} }
답변
이제 ES6에서는이 작업을 매우 쉽게 수행 할 수있는 매우 강력한 스프레드 연산자 (… Object)가 있습니다. 다음과 같이 수행 할 수 있습니다.
let alerts = {
1: { app: 'helloworld', message: 'message' },
2: { app: 'helloagain', message: 'another message' }
}
//now suppose you want to add another key called alertNo. with value 2 in the alerts object.
alerts = {
...alerts,
alertNo: 2
}
그게 다야. 원하는 키가 추가됩니다. 도움이 되었기를 바랍니다!!
답변
경고 제안 배열을 실제로 사용해야하지만 언급 한 객체에 추가하면 다음과 같습니다.
alerts[3]={"app":"goodbyeworld","message":"cya"};
그러나 이름이 모든 것을 인용하고 함께 갈 때 리터럴 숫자를 사용해서는 안됩니다.
alerts['3']={"app":"goodbyeworld","message":"cya"};
또는 객체의 배열로 만들 수 있습니다.
액세스하는 것 같습니다
alerts['1'].app
=> "helloworld"
