我有一个包含对象和数组的嵌套数据结构。我如何提取信息,即访问一个特定的或多个值(或键)?
例如:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
我如何访问项目中的第二个项目的名称?
我有一个包含对象和数组的嵌套数据结构。我如何提取信息,即访问一个特定的或多个值(或键)?
例如:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
我如何访问项目中的第二个项目的名称?
当前回答
这里有4种不同的方法来获得javascript的object属性:
Var数据= { 42岁的代码: 项目:[{ id: 1、 名称:“foo” }, { id: 2 名称:“酒吧” }) }; //方法1 让method1 = data.items[1].name; console.log (method1); //方法二 Let method2 = data.items[1]["name"]; console.log (method2); //方法3 Let method3 = data["items"][1]["name"]; console.log (method3); //方法四解构 让{items: [, {name: second_name}]} =数据; console.log (second_name);
其他回答
我更喜欢JQuery。它更干净,更容易阅读。
$.each($.parseJSON(data), function (key, value) {
alert(value.<propertyname>);
});
您可以通过这种方式访问它
data.items[1].name
or
data["items"][1]["name"]
两边相等。
在2020年,你可以使用@babel/plugin-proposal-optional- chains,它很容易访问对象中的嵌套值。
const obj = {
foo: {
bar: {
baz: class {
},
},
},
};
const baz = new obj?.foo?.bar?.baz(); // baz instance
const safe = new obj?.qux?.baz(); // undefined
const safe2 = new obj?.foo.bar.qux?.(); // undefined
https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining
https://github.com/tc39/proposal-optional-chaining
我的stringdata来自PHP文件,但仍然,我在var中表示这里。当我直接把我的json放入obj时,它不会显示什么,这就是为什么我把我的json文件作为
var obj = JSON.parse (stringdata); 所以之后,我得到消息obj,并显示在警告框,然后我得到数据,这是json数组和存储在一个变量ArrObj,然后我读取该数组的第一个对象的键值像这个ArrObj[0].id
var stringdata={
"success": true,
"message": "working",
"data": [{
"id": 1,
"name": "foo"
}]
};
var obj=JSON.parse(stringdata);
var key = "message";
alert(obj[key]);
var keyobj = "data";
var ArrObj =obj[keyobj];
alert(ArrObj[0].id);
// const path = 'info.value[0].item'
// const obj = { info: { value: [ { item: 'it works!' } ], randominfo: 3 } }
// getValue(path, obj)
export const getValue = ( path , obj) => {
const newPath = path.replace(/\]/g, "")
const arrayPath = newPath.split(/[\[\.]+/) || newPath;
const final = arrayPath.reduce( (obj, k) => obj ? obj[k] : obj, obj)
return final;
}