【问题标题】:How to get json data from a api where there are the same names as values如何从与值同名的api获取json数据
【发布时间】:2021-10-15 04:11:54
【问题描述】:

我想创建一个在 json 中搜索数据的系统。所以我在rest api上有json。 api 是这样的

[
    {
    "info": "cute but big animal",
    "type": "pig",
    "name": "patty"
    },
    {
    "info": "Barks all the time",
    "type": "dog",
    "name": "parker"
    },
    {
    "info": "Makes delicious eggs",
    "type": "chicken",
    "name": "chicky"
    }
]

有很多同名的值。

我在谷歌上搜索了很多,但他们都说我需要编号。 data.value[1]

我希望能够搜索 patty 并获取信息并输入 只需获取 json 数据

Javascript 或 nodeJS

【问题讨论】:

  • 这能回答你的问题吗? JS search in object values
  • 当您搜索patty 时,您期望得到什么结果?
  • @AdilBimzagh 我想回复这个:{ "info": "cute but big animal", "type": "pig", "name": "patty" },
  • @HereticMonkey 我去看看

标签: javascript node.js json api rest


【解决方案1】:

如果你知道键和值,这似乎是最简单的方法:

const arrayOfObjects = [
    {
    "info": "cute but big animal",
    "type": "pig",
    "name": "patty"
    },
    {
    "info": "Barks all the time",
    "type": "dog",
    "name": "parker"
    },
    {
    "info": "Makes delicious eggs",
    "type": "chicken",
    "name": "chicky"
    }
];

const key = 'name';
const value = 'patty';
const object = arrayOfObjects.find(obj => obj[key] === value);

console.log(object);

如果你不知道密钥,这是一种可能的方法:

const arrayOfObjects = [
    {
    "info": "cute but big animal",
    "type": "pig",
    "name": "patty"
    },
    {
    "info": "Barks all the time",
    "type": "dog",
    "name": "parker"
    },
    {
    "info": "Makes delicious eggs",
    "type": "chicken",
    "name": "chicky"
    }
];

const value = 'patty';
const object = arrayOfObjects.find(
  obj => Object.values(obj).some(val => val === value)
);

console.log(object);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2018-09-03
    相关资源
    最近更新 更多