You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 17:36:01