首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何获取JSON文件中的特定数据

如何获取JSON文件中的特定数据
EN

Stack Overflow用户
提问于 2018-07-05 10:41:07
回答 4查看 57关注 0票数 3

我试图以JSON格式仅获取每个数据中的洞察力。我使用lodash按月过滤,但我不能只获得每个对象的洞察力。

代码语言:javascript
复制
let insight5 = [{
    insight: "valid",
    reportMonth: "January - June 2018"
  },
  {
    insight: "invalid",
    reportMonth: "January 2018"
  },
  {
    insight: "valid",
    reportMonth: "February 2018"
  },
  {
    insight: "valid",
    reportMonth: "March 2018"
  },
  {
    insight: "valid",
    reportMonth: "April 2018"
  },
  {
    insight: "valid",
    reportMonth: "May 2018"
  },
  {
    insight: "valid",
    reportMonth: "June 2018"
  },
];


function filterData(data, month) {
  let filtered = _.filter(data, x => x.reportMonth == month)
  return filtered[0];
}

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2018-07-05 10:44:32

要仅获得洞察力,您需要返回该属性:

代码语言:javascript
复制
return filtered.length > 0 && filtered[0].insight;

我首先检查长度,以防找不到匹配的数据。

票数 1
EN

Stack Overflow用户

发布于 2018-07-05 11:05:36

您可以使用普通的JavaScript Array.prototype.filter()Array.prototype.map()

代码:

代码语言:javascript
复制
const insight5 = [{insight: "valid",reportMonth: "January - June 2018"},{insight: "invalid",reportMonth: "January 2018"},{insight: "valid",reportMonth: "February 2018"},{insight: "valid",reportMonth: "March 2018"},{insight: "valid",reportMonth: "April 2018"},{insight: "valid",reportMonth: "May 2018"},{insight: "valid",reportMonth: "June 2018"}];

const getInsightForMonth = month => insight5
  .filter(o => o.reportMonth.includes(month))
  .map(o => o.insight);
  
console.log(getInsightForMonth('February'));

票数 1
EN

Stack Overflow用户

发布于 2018-07-05 10:51:21

试试这个。

代码语言:javascript
复制
var desiredMonth = "February";
let insight5 = [{
    insight: "valid",
    reportMonth: "January - June 2018"
  },
  {
    insight: "invalid",
    reportMonth: "January 2018"
  },
  {
    insight: "valid",
    reportMonth: "February 2018"
  },
  {
    insight: "valid",
    reportMonth: "March 2018"
  },
  {
    insight: "valid",
    reportMonth: "April 2018"
  },
  {
    insight: "valid",
    reportMonth: "May 2018"
  },
  {
    insight: "valid",
    reportMonth: "June 2018"
  },
];


const filteredData = insight5.reduce((acc, currentValue) => {
  if (currentValue.reportMonth.includes(desiredMonth)) {
    acc.push(currentValue.insight);
  }
  return acc;
}, []);
console.log(filteredData);

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51182719

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档