在对象数组中引用对象标题

时间:2019-05-15 21:06:12

标签: javascript arrays object foreach

我有一个要转换为数组的对象(下面的示例),但是转换代码会删除该键,以后需要为每个循环引用该键,但是我不知道如何保留该键。

 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

3 个答案:

答案 0 :(得分:0)

这是迭代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]);
}

答案 1 :(得分:0)

Object.entries()似乎具有您需要的所有功能。它将为输入对象的每个属性返回一个[key,value]数组。这意味着输出将是2D数组。

let array2d = Object.entries(json);
array2d.forEach(function (elem) {
    Output.push(elem[0], elem[1].property1, elem[1].property2);
});

答案 2 :(得分:0)

希望我能正确理解您的问题。要将所有值放入一个单个数组中,可以像这样:在Array.reduce上使用Object.keys

let json = { "6250": { "property1": "...", "property2": "..." }, "6177": { "property1": "...", "property2": "..." }, "5870": { "property1": "...", "property2": "..." }, "4297": { "property1": "...", "property2": "..." }, "5743": { "property1": "...", "property2": "..." } }

let result = Object.keys(json).reduce((r,c) => {
  r.push(c, ...Object.values(json[c]))
  return r
}, [])

console.log(result)