[英]I can't access to inner data of my object in js
In my online shop I want to add client order by item to orders.在我的网上商店中,我想按项目将客户订单添加到订单中。 First I click and add an Item from db.
首先,我单击并从 db 添加一个项目。 Then I pass chosen item to js.
然后我将选择的项目传递给 js。
$('#addItem').click(function () {
let itemData = $('#item').val();
console.log(itemData);
});
this is output:这是输出:
{"id":1,"business_id":401,"name":"\u067e\u06cc\u0631\u0627\u0647\u0646","discount_model":1,"special_date":0,"hot_offer":0,"percent":30,"buy_quantity":null,"prize_quantity":null,"prize_name":null,"floor_buy":null,"discount_percent":null,"is_active":1,"created_at":"2019-07-02 06:43:23","updated_at":"2019-07-02 06:44:51"}
now I want itemData.name or itemData['name'], but it says: undefined !?现在我想要 itemData.name 或 itemData['name'],但它说:未定义!?
How can I access to props?我如何获得道具?
Simply you can't call properties from string, you have to convert the String to JSON object, The below parse
method can do it.只是你不能从字符串调用属性,你必须将字符串转换为 JSON 对象,下面的
parse
方法可以做到。
itemData = JSON.parse(itemData)
Refer simple example :参考简单的例子:
var myJsonStr = '{"id":1,"business_id":401,"name":"\پ\ی\ر\ا\ه\ن","discount_model":1,"special_date":0,"hot_offer":0,"percent":30,"buy_quantity":null,"prize_quantity":null,"prize_name":null,"floor_buy":null,"discount_percent":null,"is_active":1,"created_at":"2019-07-02 06:43:23","updated_at":"2019-07-02 06:44:51"}'; var myJson = JSON.parse(myJsonStr); console.log(myJson.name);
Please try this请试试这个
$('#addItem').click(function () {
let itemData = $('#item').val();
try {
itemData = JSON.parse(itemData);
} catch(e) {
throw e;
}
console.log(itemData.name);
});
tldr; tldr; safely access nested objects in JavaScript in a super cool way.
以一种超酷的方式安全地访问 JavaScript 中的嵌套对象。
Most of the times when we're working with JavaScript, we'll be dealing with nested objects and often we'll be needing to access the innermost nested values safely.大多数情况下,当我们使用 JavaScript 时,我们将处理嵌套对象,并且经常需要安全地访问最内层的嵌套值。
Let's take this nested object as an example.我们以这个嵌套对象为例。
const user = { id: 101, email: 'jack@dev.com', personalInfo: { name: 'Jack', address: { line1: 'westwish st', line2: 'washmasher', city: 'wallas', state: 'WX' } } } const user = { id: 101, email: 'jack@dev.com', personalInfo: { name: 'Jack', address: { line1: 'westwish st', line2: 'washmasher', city: 'wallas', state :'WX' } } }
To access the name of the our user, we'll write要访问我们用户的名称,我们将编写
const name = user.personalInfo.name; const name = user.personalInfo.name; const userCity = user.personalInfo.address.city;
const userCity = user.personalInfo.address.city;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.