【问题标题】:How to get value based on key from an array of objects javascript如何根据对象数组中的键获取值javascript
【发布时间】:2021-09-13 08:18:12
【问题描述】:

我有一个从数据库中获取的数组,如下所示

var sampleArray = 
{ID:1, ANALYSIS_NAME : "name1",
   custodians:"[{\"ID\": 1, \"NAME\": \"abc\"}, 
                {\"ID\": 2, \"NAME\": \"xyz\"}, 
                {\"ID\": 3, \"NAME\": \"pqr\"}]"

};

如何从上述数组中获取名称。我可以显示 console.log(sampleArray.custodians) 但是当我尝试显示 console.log(sampleArray.custodians.name) 时,我收到错误 Cannot read property 'NAME' of undefined

return(<div>
<Panel>test</panel>
/*custodians should come here*/
</div>)

如何显示上面的对象?请帮忙。提前致谢

【问题讨论】:

  • custodians的值是JSON,所以你首先要解析它-> JSON.parse()
  • sampleArray 不是数组而是对象。此外,custodians 被字符串化(序列化为文本)。

标签: javascript jquery arrays reactjs javascript-objects


【解决方案1】:

部分问题是因为 sampleArray.custodians 是 JSON 格式的字符串。您需要在访问它之前对其进行反序列化。

问题的另一部分是反序列化的结果会将custodians 转换为数组,因此您需要通过索引或循环直接访问它。

var sampleArray = {
  ID: 1,
  ANALYSIS_NAME: "name1",
  custodians: "[{\"ID\": 1, \"NAME\": \"abc\"},{\"ID\": 2, \"NAME\": \"xyz\"},{\"ID\": 3, \"NAME\": \"pqr\"}]"
};

let custodians = JSON.parse(sampleArray.custodians);

custodians.forEach(c => console.log('loop', c.NAME)); // loop

console.log('index', custodians[0].NAME); // direct access by index

-- 更新--

鉴于您的问题的更新,您可以使用map() 构建 HTML 字符串以从您的函数返回:

var sampleArray = {
  ID: 1,
  ANALYSIS_NAME: "name1",
  custodians: "[{\"ID\": 1, \"NAME\": \"abc\"},{\"ID\": 2, \"NAME\": \"xyz\"},{\"ID\": 3, \"NAME\": \"pqr\"}]"
};


let buildCustodianHtml = (data) => {
  let custodianHtml = JSON.parse(data.custodians).map(c => `<p>${c.NAME}</p>`).join('');
  return `<div><Panel>test</panel>${custodianHtml}</div>`;
}

$('#container').append(buildCustodianHtml(sampleArray));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container"></div>

【讨论】:

  • 我已经编辑了我的问题。如何在添加注释的代码中显示 /*custodians should come here*/
  • 我更新了我的答案,向您展示如何做到这一点
【解决方案2】:

custodians 属性是一个字符串。您首先需要将此字符串转换为 JSON 使用

var custodians = JSON.parse(sampleArray.custodians);

然后您可以使用它访问它

console.log(custodians[0].NAME)

【讨论】:

  • 我已经编辑了我的问题。如何在添加注释的代码中显示 /*custodians should come here*/
【解决方案3】:

由于custodians是字符串,需要先转换成对象才能访问“NAME”。

使用 JavaScript 的内置 JSON.Parse()

var sampleArray = 
    {
    ID:1, ANALYSIS_NAME : "name1",
    custodians:`[{\"ID\": 1, \"NAME\": \"abc\"}, 
                {\"ID\": 2, \"NAME\": \"xyz\"}, 
                {\"ID\": 3, \"NAME\": \"pqr\"}]`

};

let newObj = JSON.parse(sampleArray.custodians);

for(let i=0; i<newObj.length; i++){
    console.log(`Name: ${newObj[i]["NAME"]}`);
}

【讨论】:

  • 我已经编辑了我的问题。如何在添加注释的代码中显示 /*custodians should come here*/
猜你喜欢
  • 2022-01-02
  • 2021-09-13
  • 1970-01-01
  • 1970-01-01
  • 2020-04-06
  • 2020-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多