programing

개체에 추가

codeshow 2023. 8. 10. 21:47
반응형

개체에 추가

경고 및 경고에 대한 몇 가지 정보가 포함된 개체가 있습니다.

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

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()를 사용하는 모든 값과 Object.entries()를 사용하는 키-값 쌍을 가져올 수 있습니다.

var alerts = { 
    1: {app:'helloworld',message:'message'},
    2: {app:'helloagain',message:'another message'}
}
console.log(Object.keys(alerts))
// Output
Array [ "1", "2" ]

jQuery$.extend(obj1, obj2)두 개체를 병합할 수 있지만 실제로 어레이를 사용해야 합니다.

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

다음과 같이 확산 구문을 사용할 수 있습니다.

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

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

ES6에는 매우 강력한 스프레드 연산자가 있습니다(...객체) 이 작업을 매우 쉽게 만들 수 있습니다.다음과 같이 수행할 수 있습니다.

let alerts = {
  1: {
    app: 'helloworld',
    message: 'message'
  },
  2: {
    app: 'helloagain',
    message: 'another message'
  }
}
console.log("----------------before----------------");
console.log(alerts);
//now suppose you want to add another key called alertNo. with value 2 in the alerts object. 

alerts = {
  ...alerts,
  alertNo: 2
}

console.log("----------------After----------------");
console.log(alerts);
.as-console-wrapper {
  max-height: 100%!important;
}

바로 그거야.원하는 키가 추가됩니다.이것이 도움이 되길 바랍니다!!

다른 답변과 마찬가지로 어레이를 사용하는 것이 더 쉬울 수 있습니다.

그렇지 않은 경우:

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

경고 제안의 배열을 따라야 하지만 그렇지 않으면 언급한 개체에 추가하면 다음과 같습니다.

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

하지만 이름이 모든 것을 따옴표로 묶어서 문자 그대로의 숫자를 사용해서는 안 되기 때문에.

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

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

액세스하는 방법은 다음과 같습니다.

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

가장 바깥쪽 구조를 배열로 변경할 수 있는 기능이 있습니까?그래서 이것은 이렇게 보일 것입니다.

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

따라서 하나를 추가해야 할 때는 어레이에 밀어넣으면 됩니다.

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

그런 다음 오류를 열거하는 방법에 대한 제로 기반 인덱스가 기본으로 제공됩니다.

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

미안하지만 이미 내 평판 때문에 당신의 답변에 대해 코멘트할 수 없습니다! ...그래서, 당신이 당신의 객체의 구조를 수정하고 싶다면, 당신은 Thane Pummer가 말하는 것처럼 해야 합니다. 하지만 당신이 아이템을 어디에 둘지 신경쓰지 않는다면, 그것은 삽입할 번호를 지정하지 않으면 첫 번째 위치에 삽입될 것입니다.

예를 들어 Json 개체를 mongoDB 함수 호출에 전달하고 수신한 조건 내에 새 키를 삽입하려는 경우 이 기능은 매우 유용합니다.이 경우 내 코드 내 변수의 정보가 포함된 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();
}

대안으로 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);

[Javascript] 약간의 속임수를 쓴 후에, 이것은 저에게 효과가 있었습니다.

 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은 날짜와 시간만 다릅니다.

사용해 보십시오.

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

꽤 잘 작동합니다. 배열의 시작 부분에 추가할 것입니다.

언급URL : https://stackoverflow.com/questions/617036/appending-to-an-object

반응형