JavaScript 数组对象 新增对象到数组 根据key判断没有则添加,有则替换

var problems = []
const problem1 = {
	problemUuid: 1,
	voteState: 2
}
const problem2 = {
	problemUuid: 2,
	voteState: 1
}
const problem3 = {
	problemUuid: 2,
	voteState: 2
}
// 过滤
/**
 * @param {Object} 新数组
 * @param {Object} 对象
 * @param {Object} key
 */
function formateArrObjData(initialArr, obj, pro) {
	let index = initialArr.findIndex((val) => val[pro] === obj[pro])
	// 如果有就替换  没有就添加
	if (initialArr.findIndex((val) => val[pro] === obj[pro]) !== -1) {
		problems.splice(index, 1, obj);
	} else {
		problems.push(obj);
	}
	return problems
}
formateArrObjData(problems,problem1,'problemUuid')
formateArrObjData(problems,problem2,'problemUuid')
formateArrObjData(problems,problem3,'problemUuid')
console.log(problems)

你可能感兴趣的:(javascript,开发语言,ecmascript)