如何基于属性从JSOn中删除?

时间:2018-07-05 06:19:06

标签: jquery

我有如下的JSON

[{
        "name": "Mike",
        "incentives": "23.45"
    },
    {
        "name": "Larsen",
        "incentives": "34.78",
        "newlyadded": true
    },
    {
        "name": "Steve",
        "incentives": "26.78"
    }
]

我需要删除所有包含新添加的

属性的JSON对象。

我这样尝试过

myjson = myjson.filter((obj) => myjson.indexOf(obj.newlyadded) === true);

https://jsfiddle.net/o2gxgz9r/54476/

能否请您告诉我如何进行这项工作

2 个答案:

答案 0 :(得分:1)

您需要检查obj.newlyadded是否丢失或错误,因为.filter仅保留返回true的值。

var myjson = [{
		"name": "Mike",
		"incentives": "23.45"
	},
	{
		"name": "Larsen",
		"incentives": "34.78",
		"newlyadded": true
	},
	{
		"name": "Steve",
		"incentives": "26.78"
	}
];

myjson = myjson.filter((obj) => typeof obj.newlyadded === 'undefined' || obj.newlyadded !== true);

console.log(JSON.stringify(myjson))

答案 1 :(得分:1)

尝试一下。  有关hasOwnProperty

的更多详细信息

$(document).ready(function() {
 
 
 var myjson = [{
		"name": "Mike",
		"incentives": "23.45"
	},
	{
		"name": "Larsen",
		"incentives": "34.78",
		"newlyadded": true
	},
	{
		"name": "Steve",
		"incentives": "26.78"
	}
];



json = myjson.filter((obj) => obj.hasOwnProperty('newlyadded') === false);

console.log(JSON.stringify(json))
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>