简体   繁体   English

从JavaScript对象检索属性

[英]Retrieve property from JavaScript object

Update: This code just works :) Other logic in my page caused a problem 更新:此代码才有效:)我页面中的其他逻辑导致了问题

I'm reading out a JavaScript object from a jQuery data object: 我正在从jQuery数据对象中读取一个JavaScript对象:

$('body').data('myvals', {var1:"lorem",var2:"ipsum",var3:"dolores",var4:"amet"});
var obj = $('body').data('myvals');

I can successfully access the contents of this object 我可以成功访问该对象的内容

console.log(Object.entries(obj));

This returns (in Firefox console): 返回结果(在Firefox控制台中):

[["var1", "lorem"], ["var2", "ipsum"], ["var3", "dolores"], ["var4", "amet"]]

But I don't succeed in retrieving a specific property (getting 'lorem' by accessing 'var1'). 但是我没有成功检索特定属性(通过访问“ var1”获得“ lorem”)。 Following attempts return undefined : 以下尝试返回undefined

console.log(obj.var1);
console.log(obj[var1]);

What am I doing wrong? 我究竟做错了什么?

This : 这个 :

[["var1", "lorem"], ["var2", "ipsum"], ["var3", "dolores"], ["var4", "amet"]]

is an array with indexes as keys.Its is not an Object (Even though in Javascript pretty much everything is an Object) So when you try obj.var1 you will get undefined. 是一个以索引为键的数组。它不是一个对象(即使在Javascript中几乎所有的东西都是一个对象),所以当您尝试obj.var1时,将得到未定义。 Cause there is no obj.var1 in there. 因为那里没有obj.var1。 There is obj[0] which holds array("var1", "lorem"); 有obj [0],它保存着array(“ var1”,“ lorem”); inside it. 在里面。

This : 这个 :

{"var1":"lorem"}, {"var2":"ipsum"},{"var3":"dolores"},{"var4":"amet"}

is an Object , in this one if you type console.log(obj.var1) you will get "lorem". 是一个Object,在这个对象中,如果您输入console.log(obj.var1),您将得到“ lorem”。

You added more code since i replied so i knopw need to change my annswer. 自从我回答以来,您添加了更多代码,所以我知道需要更改答案。 Your issue is " Object.entries() " , this will return an Array , you need to use 您的问题是“ Object.entries() ”,这将返回一个Array ,您需要使用

Object.keys(obj) .forEach(function(key){
 console.log(key);
});

Addition Your question layout and provided info have been a bit confusing. 另外,您的问题布局和提供的信息有些混乱。 Avoiding what you wrote at the start and focusing only on your last addition to your question , your only error is the: 避免一开始就写什么,而只关注最后添加的问题,唯一的错误是:

console.log(obj[var1]);

it should be 它应该是

console.log(obj["var1"]);

Other than that it should work as expected. 除此之外,它应能按预期工作。

this works just fine, I don't see what's the problem: DEMO 这很好,我看不出问题所在: DEMO

$('body').data('myvals', {var1:"lorem",var2:"ipsum",var3:"dolores",var4:"amet"});
var obj = $('body').data('myvals');
console.log(obj.var1);
console.log(obj['var1']);

if the code above doesn't work try console.log($('body').data('myvals')); 如果上面的代码不起作用,请尝试console.log($('body').data('myvals')); and see if it returns any value. 并查看它是否返回任何值。

if it returns undefined then you've probably forgotten to use document ready, just try wrapping your code in $(function(){ ... }) 如果返回未定义,则您可能已经忘了准备好使用文档,只需尝试将代码包装在$(function(){ ... })

You can access the entries returned as pairs from Object.entries using destructuring as below: 您可以使用以下解构访问从Object.entries成对返回的条目:

Object.entries(obj).forEach(([key, value]) => {
  console.log(key);
  console.log(value);
})

An alternative way to iterate using for-of loop 使用for-of循环进行迭代的另一种方法

 let obj = { one: 1, two: 2 }; for (let [k,v] of Object.entries(obj)) { console.log(`${k}: ${v}`); } 

Instead of printing Object.entries(obj) to the console, it would be clearer for you to print the object itself to the console. 与将Object.entries(obj)打印到控制台相比,将对象本身打印到控制台将更加清晰。 The entry list is a distraction from the issue you're dealing with. 条目列表分散了您正在处理的问题的注意力。 What I mean is this: 我的意思是:

var obj = $('body').data('myvals');
console.log(obj);

//or this
console.log(JSON.stringify(obj));

That will show you the actual content of the associative array. 这将向您显示关联数组的实际内容。 From there, either of these should work. 从那里,这两个都应该起作用。 Don't forget to use string quotes for the array index: 不要忘记为数组索引使用字符串引号:

console.log(obj.var1);
console.log(obj["var1"]); // obj[var1] is incorrect, need quotes

If you see "var1" as a key in the full object printout above, then individual property should also be shown here. 如果您在上面的完整对象打印输出中看到“ var1”作为键,则此处也应显示单个属性。 Otherwise, some other part of your code must have made changes to the content of obj or $('body).data('myvals') by the time you extract "var1" 否则,您的代码的其他部分必须在提取“ var1”时更改了obj$('body).data('myvals')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM