javascript - 访问 javascript 对象失败

标签 javascript php arrays json

我有像这张图片这样的 json 数据,它是我从 PHP 获得的。 enter image description here

我想访问来自 json 的所有数据。 对于我当前的情况,我想将现有数据与来自 Json 的数据进行匹配。

enter image description here

但是我有一点错误。我的所有数据都与 Json 数据不同。 虽然必须有一些合适的数据。

enter image description here

这是我的代码

const dataArr = <?= $ar; ?>;
console.log(dataArr); //image 1
var mySVG = document.getElementById("alphasvg");
var svgDoc;
mySVG.addEventListener("load",function() {

    svgDoc = mySVG.contentDocument.documentElement;
    var xd = svgDoc.getElementsByTagName("rect");

        for(i=0;i<xd.length;i++){
            let get_a = xd[i].getAttribute('id');
            for(x = 1; x<= 30; x++){
                for(y=0; y<=4; y++){
                    if(get_a == 'rect' + x + '_child' + y){
                        //console.log(get_a); //img2
                        if(dataArr[(x-1)*y].idval.includes(get_a) == true){
                            console.log('yes u good');
                        } else {
                            console.log('error');
                        }
                    }
                }
            }
        }
    }, false);

有人能帮帮我吗?

编辑:console.log(get_a,dataArr[(x-1)*y]); 的结果 enter image description here 我的数据不匹配。

最佳答案

如果您只是想在数组中的对象中搜索特定的键 - idval - 以及它的值,您可以使用简单的 for 循环,例如:

for (var a = 0; a < dataArr.length; a++) {
  if (dataArr[a].idval == get_a) {
    console.log("there it is", dataArr[a]);
    break;
  }
}

这是一个例子:

var dataArr = [{
    id: "test",
    lantai: 1,
    status_asrama: "tersedia",
    idval: "rect_child1"
  },
  {
    id: "anothertest",
    lantai: 2,
    status_asrama: "tersedia",
    idval: "rect_child2"
  }, {
    id: "finaltest",
    lantai: 3,
    status_asrama: "tersedia",
    idval: "rect_child3"
  }
];

let get_a = "rect_child2";

for (var a = 0; a < dataArr.length; a++) {
  if (dataArr[a].idval == get_a) {
    console.log("there it is", dataArr[a]);
    break;
  }
}

关于javascript - 访问 javascript 对象失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56779818/

相关文章:

php - 将多个值从下拉 View 发送到 Controller 操作

javascript - 使用 lodash 从数组中的对象中过滤掉唯一值

javascript - php中条件语句后的模态框

javascript - Chrome 扩展 : How to remove content script after injection?

javascript onload 不工作但 onclick 工作 css 画线

javascript - Laravel mix 编译 - 找不到类

php - 从十六进制获取 PHP 中的最低有效位

php - 返回 MySQL "group by"限制组

javascript - 如何从此数据结构中删除 javascript 对象中的数据?

javascript - 将单词列表转换为数组