Подтвердить что ты не робот

как удалить ключ и значение объекта json.

У меня есть объект json, как показано ниже. где я хочу удалить запись "otherIndustry" и ее значение, используя приведенный ниже код, который не работает.

var updatedjsonobj = delete myjsonobj['otherIndustry'];

Как удалить специфический ключ объекта Json и его значение. Ниже мой пример объекта json, где я хочу удалить ключ "otherIndustry" и его значение.

var myjsonobj =  {
      "employeeid": "160915848",
      "firstName": "tet",
      "lastName": "test",
      "email": "[email protected]",
      "country": "Brasil",
      "currentIndustry": "aaaaaaaaaaaaa",
      "otherIndustry": "aaaaaaaaaaaaa",
      "currentOrganization": "test",
      "salary": "1234567"
    };
delete myjsonobj ['otherIndustry'];
console.log(myjsonobj);

где журнал все еще печатает один и тот же объект, не удаляя запись "otherIndustry" с объекта.

4b9b3361

Ответ 1

оператор delete используется для remove property объекта.

delete оператор не возвращает новый объект, возвращает boolean: true или false.

С другой стороны, после интерпретации выполняет var updatedjsonobj = delete myjsonobj['otherIndustry']; , updatedjsonobj переменная будет хранить boolean значение.

Как удалить конкретный ключ объекта Json и его значение?

Вам просто нужно знать имя свойства, чтобы удалить его из свойств объекта.

delete myjsonobj['otherIndustry'];

let myjsonobj = {
  "employeeid": "160915848",
  "firstName": "tet",
  "lastName": "test",
  "email": "[email protected]",
  "country": "Brasil",
  "currentIndustry": "aaaaaaaaaaaaa",
  "otherIndustry": "aaaaaaaaaaaaa",
  "currentOrganization": "test",
  "salary": "1234567"
}
delete myjsonobj['otherIndustry'];
console.log(myjsonobj);

Ответ 2

Следуйте этому, это может быть похоже на то, что вы ищете:

var obj = {
    Objone: 'one',
    Objtwo: 'two'
};

var key = "Objone";
delete obj[key];
console.log(obj); // prints { "objtwo": two}

Ответ 3

Вот еще один пример. (проверьте ссылку)

const myObject = {
  "employeeid": "160915848",
  "firstName": "tet",
  "lastName": "test",
  "email": "[email protected]",
  "country": "Brasil",
  "currentIndustry": "aaaaaaaaaaaaa",
  "otherIndustry": "aaaaaaaaaaaaa",
  "currentOrganization": "test",
  "salary": "1234567"
};
const {otherIndustry, ...otherIndustry2} = myObject;
console.log(otherIndustry2);
.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}

Ответ 4

У меня были проблемы с попыткой удалить возвращенный объект JSON и я обнаружил, что это на самом деле строка. Если вы удалили JSON.parse() перед удалением, вы можете быть уверены, что ваш ключ будет удален.

let obj;
console.log(this.getBody()); // {"AED":3.6729,"AZN":1.69805,"BRL":4.0851}
obj = this.getBody();
delete obj["BRL"];
console.log(obj) // {"AED":3.6729,"AZN":1.69805,"BRL":4.0851}
obj = JSON.parse(this.getBody());
delete obj["BRL"];
console.log(obj) // {"AED":3.6729,"AZN":1.69805}

Ответ 5

Есть несколько способов сделать это, давайте посмотрим на них один за другим:

  1. метод удаления: самый распространенный способ

const myObject = {
    "employeeid": "160915848",
    "firstName": "tet",
    "lastName": "test",
    "email": "[email protected]",
    "country": "Brasil",
    "currentIndustry": "aaaaaaaaaaaaa",
    "otherIndustry": "aaaaaaaaaaaaa",
    "currentOrganization": "test",
    "salary": "1234567"
};

delete myObject['currentIndustry'];
// OR delete myObject.currentIndustry;
  
console.log(myObject);

Ответ 6

у меня есть два ключа "dateTo" с тем же именем, я хочу удалить только один из первого адреса, это возможно:

            "addresses":
                        [
                            {
                                "houseNumber":"3", "address1":"Rowlands Close",
                                "townCity":"Training Town", "postcode":"IV44 8TZ",
                                "dateTo":"2019-12-31", "dateFrom":"2016-01-1"
                            },
                {
                                "houseNumber":"5", "address1":"Rowlands Close",
                                "townCity":"Training Town", "postcode":"IV44 8TZ",
                                "dateTo":"2015-12-31", "dateFrom":"2013-01-1"
                            }

                        ]