标签云

微信群

扫码加入我们

WeChat QR Code

This question already has an answer here:How do I remove a property from a JavaScript object?38 answersif I have a JSON object say:var myObj = {'test' : {'key1' : 'value', 'key2': 'value'}}can I remove 'key1' so it becomes:{'test' : {'key2': 'value'}}


Just to be pedantic, that's a Javascript object, not a "JSON object"JSON is the string representation of Javascript object.

2019年05月22日36分51秒

delete myObj.test['key1']; would work as well.

2019年05月22日36分51秒

So would delete myObj['test']['key1']; you can interchange whatever.x and whatever['x'] as long as x is a valid variable name, so even delete myObj['test'].key1 would work.

2019年05月22日36分51秒

fiddle.jshell.net/jr0enbua Here is an example using delete

2019年05月22日36分51秒

This is the best JavaScript keyword I have ever seen !

2019年05月22日36分51秒

It may be worth noting that the delete keyword mutates the Object which is frequently not exactly the intended behavior.One way to maintain immutability (for flat objects) is to make use of the Object.assign or spread operator to shallow clone prior to performing the delete.

2019年05月22日36分51秒

i like the option for dynamism. it helped in my own case to remove a property dynamically from a json object

2019年05月22日36分51秒

When checking the solution above, already think about what is the solution if it is a variable, thanks for saving my time for the trick

2019年05月22日36分51秒

Hey praneetloke I have one query I get JSON array Ex: [{\"Countrycode\":\"DE\",\"count\":\"3\"}] but i want to get like[{"DE":"3"}] like this but i don't get this output Please help me

2019年05月22日36分51秒

Brij your question is not related to the question on this page. Without much context about your question, I can only say that you should look at lodash.com/docs/4.17.4#map from Lodash. The map function will allow you to create a new array that has the value of the original array's CountryCode as the key in the new array, and the value of the count property from original array as the value in the new array. If this doesn't help, you should start a new question on Stackoverflow. You may also want to see if you can have the server return the response the way that you want it.

2019年05月22日36分51秒

ggb667 you don't need to. Ordering doesn't matter for a JSON object. Without getting too deep in my explanation, it's like a Dictionary (or Map). Order matters if you are dealing with an array that contains objects or other values, since they don't have a "key". Arrays use a position based index, which is why you would always access values in an array using integer based indices.

1970年01月01日00分06秒