【问题标题】:Return key and value from object if value equals如果值等于,则从对象返回键和值
【发布时间】:2020-07-19 04:10:07
【问题描述】:

typeof value 等于某个值时,我能否仅从具有多个键的对象中返回键/值对?

 var recs = {
                "user_name": "C_51",
                "num1": 51,
                "num2": 101,
                "num3": 151
            },
            {
                "metric": 4461996.0,
                "title": "v_revenue"
            }
Object.values(recs).forEach(k => {
    if (typeof k == 'string') {
        //then show:
        {"user_name": "C_51"},
       {"title": "v_revenue"}
    }
});

有没有办法做到这一点?

【问题讨论】:

  • recs 是语法错误。
  • Object.values() 方法返回给定对象自己的可枚举属性值的数组。你的理解是完全错误的。见Object.values
  • @StackSlave 这是一个逻辑错误而不是语法错误。 if (typeof Object.values(recs) == 'string') 是合法的代码行 - 它永远是错误的。
  • 我编辑了它。我做了一个 forEach 然后循环遍历每个
  • @RamblinRose 和 OP,第一个代码块是无效对象。

标签: javascript jquery html json object


【解决方案1】:

你的代码……有点乱。但是你想要做什么的核心想法并不难。

如果你有:

const recs = {
    "user_name": "C_51",
    "num1": 51,
    "num2": 101,
    "num3": 151
};

你可以做...

const entries = Object.entries(recs);
const entryObjects = entries.map(name, value) => ({ [name]: value });

然后 entryObjects 将是由recs 的“条目”组成的对象数组。

【讨论】:

  • @machineghost,但我只想要字符串。我不想要 "num1": 51, "num2": 101, "num3": 151 我只想要 "user_name": "C_51"
  • 哦,那就更简单了:const { user_name } = recs; const yourNewObject = { user_name };。如果您有其他您关心的属性,只需将它们添加到其中,例如。 const { user_name, foo } = recs; const yourNewObject = { foo, user_name };
猜你喜欢
  • 2020-12-08
  • 2019-04-29
  • 2017-07-15
  • 1970-01-01
  • 1970-01-01
  • 2022-12-17
  • 2020-11-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多