객체에 추가


156

경고와 경고에 대한 정보를 보유한 개체가 있습니다.

var alerts = { 
    1: { app: 'helloworld', message: 'message' },
    2: { app: 'helloagain', message: 'another message' }
}

이 외에도 몇 개의 경고가 있는지 알려주는 변수가 있습니다 alertNo. 내 질문은 새 경고를 추가 할 때 경고를 alerts객체 에 추가하는 방법이 있습니까?


6
게시 한 json에 문제가 있다고 생각합니다. 1 : {app : 'helloworld', 'message'} => 1 : {app : 'helloworld', message : 'a message'}?
Andreas Grech

답변:


235

경고를 단일 객체의 속성 대신 배열에 레코드로 저장하는 것은 어떻습니까?

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'});

1
이 답변은 경고의 ID가 추가 될 것으로 기대합니다. 글쎄, 당신이 이미 그것을 알고 있다면, 당신은 단순히 원래 객체 형식을 따르고 다음을 수행 할 수 있습니다 : alerts[3] = { app: 'hello3', message: 'message 3' }. 이를 통해 ID별로 메시지에 액세스 할 수 있습니다 alerts[2] => { app: 'helloworld', message: 'message' }. 길이를 얻는 것은 다음과 같습니다 : Object.keys(alerts).length(비트 배열에서 더 쉽습니다)
Matt

61

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);

JQuery의 확장 속도가 느립니다 ( trevmex.com/post/2531629773/jquerys-extend-is-slow) . 또한 오타가 있습니다. $ .extends ()는 $ .extend ()를 읽어야합니다.
ken

오타를 잘 잡습니다. $ .extends가 도움이되는 상황이 있지만 가능하면 피해야 할 경우가 있습니다.
respectTheCode

1
괄호없이 하나의 레코드 구조 만 가지고 있으면 extend ()가 정상이라고 생각합니다. 나머지는 respectTheCode에 동의하기 위해 push ()를 사용하십시오.
elvenbyte

39

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" ]

7
다른 사람들이 객체를 배열로 변환하는 것을 언급하기 때문에 이것은 실제로 정답입니다. 그러나이 방법으로 객체로 객체를 유지합니다. 저자의 경우 배열을 사용하는 것이 더 좋았지 만 이것이 객체에 추가하는 방법에 대한 대답입니다.
Goran Jakovljevic

2
그렇습니다. 동의합니다. 질문에 객체의 배열이 없으며 단지 객체이므로 이것이 완벽한 답입니다!
키샨 오자

이것은 정답입니다. 새 객체를 추가 할 인덱스를 어떻게 알 수 있습니까?
Capan

1
이것이 제목 질문에 대한 답변입니다.
FistOfFury

11

다른 답변에서 지적했듯이 배열을 사용하는 것이 더 쉽다는 것을 알 수 있습니다.

그렇지 않은 경우 :

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


경고를 삭제하거나 키를 건너 뛴 경우에는 작동하지 않습니다. 당신의 라인을 따라 뭔가를 추가해야합니다 while(alerts[size]) size++;그리고 아마 이름 바꾸기 sizenewId.
까지

11

다음과 같이 스프레드 구문을 사용할 수 있습니다.

var alerts = { 
1: { app: 'helloworld', message: 'message' },
2: { app: 'helloagain', message: 'another message' }
 }

alerts = {...alerts, 3: {app: 'hey there', message: 'another message'} }

7

이제 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
 }

그게 다야. 원하는 키가 추가됩니다. 도움이 되었기를 바랍니다!!


6

경고 제안 배열을 실제로 사용해야하지만 언급 한 객체에 추가하면 다음과 같습니다.

alerts[3]={"app":"goodbyeworld","message":"cya"};

그러나 이름이 모든 것을 인용하고 함께 갈 때 리터럴 숫자를 사용해서는 안됩니다.

alerts['3']={"app":"goodbyeworld","message":"cya"};

또는 객체의 배열로 만들 수 있습니다.

액세스하는 것 같습니다

alerts['1'].app
=> "helloworld"

5

가장 바깥 쪽 구조를 배열로 변경할 수 있습니까? 이렇게 보일 것입니다

var alerts = [{"app":"helloworld","message":null},{"app":"helloagain","message":"another message"}];

따라서 하나를 추가해야 할 때 배열로 밀어 넣을 수 있습니다.

alerts.push( {"app":"goodbyeworld","message":"cya"} );

그런 다음 오류가 열거되는 방법에 대한 기본 제공 인덱스 (0부터 시작)가 있습니다.


2

ES6로 더 쉽게 :

let exampleObj = {
  arg1: {
    subArg1: 1,
    subArg2: 2,
  },
  arg2: {
    subArg1: 1,
    subArg2: 2,
  }
};

exampleObj.arg3 = {
  subArg1: 1,
  subArg2: 2,
};

console.log(exampleObj);

{
arg1: {subArg1: 1, subArg2: 2}
arg2: {subArg1: 1, subArg2: 2}
arg3: {subArg1: 1, subArg2: 2}
}

0

대안으로, ES6에서는 스프레드 구문이 사용될 수 있습니다. 경고를 위해 ${Object.keys(alerts).length + 1}다음 id을 반환 합니다.

let alerts = { 
    1: {app:'helloworld',message:'message'},
    2: {app:'helloagain',message:'another message'}
};

alerts = {
  ...alerts, 
  [`${Object.keys(alerts).length + 1}`]: 
  { 
    app: `helloagain${Object.keys(alerts).length + 1}`,message: 'next message' 
  } 
};

console.log(alerts);


0

미안하지만 이미 명성으로 인해 답변에 댓글을 달 수 없습니다! ... 따라서 객체의 구조를 수정하려면 Thane Plummer가 말한 것처럼 해야 하지만 어디에 신경 쓰지 않으면 약간의 트릭이 필요합니다. 항목을 넣으려면 : 삽입 번호를 지정하지 않으면 첫 번째 위치에 삽입됩니다.

예를 들어 monsonDB 함수 호출에 Json 객체를 전달하고 수신 한 조건 내에 새 키를 삽입하려는 경우에 유용합니다. 이 경우 코드 내 변수의 일부 정보와 함께 myUid 항목을 삽입합니다.

// From backend or anywhere
let myUid = { _id: 'userid128344'};
// ..
// ..

  let myrequest = { _id: '5d8c94a9f629620ea54ccaea'};
  const answer = findWithUid( myrequest).exec();

// ..
// ..

function findWithUid( conditions) {
  const cond_uid = Object.assign({uid: myUid}, conditions);
  // the object cond_uid now is:
  // {uid: 'userid128344', _id: '5d8c94a9f629620ea54ccaea'}
  // so you can pass the new object Json completly with the new key
  return myModel.find(cond_uid).exec();
}


0

[자바 스크립트] 약간의 혼란스러운 포커 이후에 이것은 나를 위해 일했습니다.

 let dateEvents = (
            {
                'Count': 2,
                'Items': [
                    {
                        'LastPostedDateTime': {
                            "S": "10/16/2019 11:04:59"
                        }
                    },
                    {
                        'LastPostedDateTime': {
                            "S": "10/30/2019 21:41:39"
                        }
                    }
                ],
            }
        );
        console.log('dateEvents', dateEvents);

내가 해결해야 할 문제는 여러 이벤트가있을 수 있으며 모두 같은 이름을 갖게된다는 것입니다. LastPostedDateTime 다른 것은 날짜와 시간입니다.


-1

이 시도:

alerts.splice(0,0,{"app":"goodbyeworld","message":"cya"});

꽤 잘 작동하며 배열의 시작 부분에 추가합니다.


객체에서 스플 라이스를 호출 할 수 없으며 배열에서만 호출 할 수 없기 때문에 작동하지 않았습니다.
Richard Woolf
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.