JS如何根据key查询对象时返回完整键值对而非仅返回对应值
问题原因
你当前的代码使用了...扩展运算符将myObj[key]对应的数组元素逐个插入结果数组,仅收集到了值内容,没有保留对应的键信息。
修复代码
const myObj = { 250: [176916, 176922, 176939], 325: [244050], 400: [177100], 500: [166743], 700: [387789], }; let arrAcceptedValues = []; let notArrAcceptedValues = []; const acceptedValues = ["250", "400"]; Object.keys(myObj).forEach((key) => { // 构造符合要求的单键值对对象 const targetItem = { [key]: myObj[key] }; acceptedValues.includes(key) ? arrAcceptedValues.push(targetItem) : notArrAcceptedValues.push(targetItem); }); console.log({ arrAcceptedValues, notArrAcceptedValues });
可选优化
如果需要返回的键是数字类型而非字符串类型,可以将构造对象的代码修改为const targetItem = { [Number(key)]: myObj[key] };,即可得到{250: [176916, 176922, 176939]}的结构。
内容的提问来源于stack exchange,提问作者Abed Aarabi
相关产品推荐
相关产品推荐

