Javascript 在对象数组中引用对象标题
我有一个正在转换为数组的对象(下面的示例),但转换代码会删除该键,并且需要在将来为每个循环引用该键,但我无法确定如何保留该键Javascript 在对象数组中引用对象标题,javascript,arrays,object,foreach,Javascript,Arrays,Object,Foreach,我有一个正在转换为数组的对象(下面的示例),但转换代码会删除该键,并且需要在将来为每个循环引用该键,但我无法确定如何保留该键 let json = { "6250": { "property1": "...", "property2": "..." }, "6177": { "property1": "...", "property2": "..." }, "5870": {
let json = {
"6250": {
"property1": "...",
"property2": "..."
},
"6177": {
"property1": "...",
"property2": "..."
},
"5870": {
"property1": "...",
"property2": "..."
},
"4297": {
"property1": "...",
"property2": "..."
},
"5743": {
"property1": "...",
"property2": "..."
}
}
function json2array(json){
var result = [];
var keys = Object.keys(json);
keys.forEach(function(key){
result.push(json[key]);
});
return result;
}
var array = json2array(json);
array.forEach(function(elem, i) {
Output.push(name, elem["property1"], elem["property2"]]);
});
例如,第一个循环中的“
name
”应该是6250
。这是迭代json的最好、最干净的方法,希望能有所帮助
let dataJson = {
"6250": {
"property1": "...",
"property2": "..."
},
"6177": {
"property1": "...",
"property2": "..."
},
"5870": {
"property1": "...",
"property2": "..."
},
"4297": {
"property1": "...",
"property2": "..."
},
"5743": {
"property1": "...",
"property2": "..."
}
}
for (let x in dataJson){
//x is the current key
console.log(x);
//getting the values of the current key
console.log(dataJson[x]);
}
似乎拥有您需要的所有功能。它将为输入对象的每个属性返回一个[key,value]数组。这意味着输出将是二维数组
let array2d = Object.entries(json);
array2d.forEach(function (elem) {
Output.push(elem[0], elem[1].property1, elem[1].property2);
});
我希望我正确地理解了你的问题。要将所有值放入一个单个数组中,您可以使用类似的:
let json={“6250”:{“property1”:“…”,“property2”:“…”,“6177”:“{“property1”:“…”,“property2”:“…”,“5870”:{“property1”:“…”,“property2”:“…”,“4297”:{“property1”:“,“property2”:“,”5743:{“property1”:“,”和“,“property2”:
让result=Object.keys(json).reduce((r,c)=>{
r、 push(c,…Object.values(json[c]))
返回r
}, [])
console.log(result)
您确定它是数组而不是对象吗?看起来你有语法错误。我的意思是,你确定第一个[
真的是[
而不是{
?为什么最后一个对象
没有像其他对象一样的ID
,请检查您的结构,澄清它是一个数组
,还是仅仅是一个对象
。更新了代码以澄清。感谢您的帮助!我觉得迭代json是一种方法,但我无法得到它。我只需要以output.push([ID,propert1,property2])结束,而我似乎无法到达那里