【问题标题】:Filtering JSON data and appending to divs过滤 JSON 数据并附加到 div
【发布时间】:2019-08-27 10:12:32
【问题描述】:

我有一个本地 JSON 文件,我正在尝试从中过滤数据并将该数据附加到我的 html 文件中的 div 中。我无法在控制台中看到数据,所以我不确定我是否错误地执行了console.log(见下文),或者数据是否基于范围“无法访问”。

JS 文件:

import $ from 'jquery';
import jsonData from "./test.json";

function _loadDispForm() {
        let dispData = jsonData.d.results.filter(x => {
            return {
                "Title": x.Title,
                "GoalRange": x.GoalRange,
                "Office": x.Office,
                "Role": x.Role,
                "IsFilled": x.IsFilled,
                "Employee": x.Employee,
                "IsActive": x.IsActive,
                "Notes": x.Notes
            }

        })      
        $("#display-form-job-title").append("Title");

        console.log(x.Title);
        console.log(JSON.stringify(dispData));
    }

JSON sn-p:

{
  "d": {
    "results": [
      {
        "FileSystemObjectType": 0,
        "Id": 1,
        "Title": "TitleHere",
        "GoalRange": "3",
        "Office": "Somewhere",
        "Role": "FPSL",
        "IsFilled": false,
        "Employee": null,
        "IsActive": true,
        "Notes": null,
        "ID": 1,
        "Attachments": false
...etc

HTML sn-p:

<div class="col-6">

  <h3 id="display-form-job-title"></h3>

大多数情况下,其他键值的 HTML 标记与此类似。

【问题讨论】:

  • 你收到json了吗
  • @Deepak 当我console.log jsonData 在函数之外我可以看到它。
  • 请参考我的解决方案
  • 1.您的“过滤器”看起来不像过滤器,它看起来像地图。你到底想在这里发生什么? 2. 这里:console.log(x.Title);,x 不存在——它只存在于这个函数内部:jsonData.d.results.filter(x =&gt; { //...
  • @mbojko 你说得对,我应该使用地图而不是过滤器。就x 而言,它是否应该可以在函数之外访问才能正确使用?

标签: javascript jquery json methods append


【解决方案1】:

正如其他答案所述,您很可能应该使用.map(“将此长度为 N 的数组变形为新的长度为 N 的数组”),而不是 .filter(“从长度 N 中返回长度

a = [1,2,3]
console.log(a.map(a => a + 1)) // [2,3,4]
console.log(a.filter(a => a == 2)) // [2]
console.log(a.filter(a => a > 1)) // [2,3]

【讨论】:

    猜你喜欢
    • 2019-07-07
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 2017-06-17
    • 2013-07-14
    相关资源
    最近更新 更多