JavaScript通过键拆分JSON对象

3

我有一个情况,需要利用键来拆分后端给出的Json对象。以下是后端提供的JSON示例:

{
    "answer": {
        "E2": "Tony Stark",
        "E3": "1",
        "E4": "2",
        "E6": "4",
        "E8": "9120",
        "E9": "01",
        "F1": "Marvel",
        "F2": "1",
        "F4": "2",
        "F6": "4",
        "F8": "9120",
        "F9": "01",
        "G1": "02",
        "G2": "02",
        "G3": "02",
        "H10": "Car"
    }
}

我能否将答案分为E、F、G和H四个部分?期望的结果是:

{
    "answer": [
        {
            "E2": "Tony Stark",
            "E3": "1",
            "E4": "2",
            "E6": "4",
            "E8": "9120",
            "E9": "01",
            "sectionName": "E"
        },
        {
            "F1": "Marvel",
            "F2": "1",
            "F4": "2",
            "F6": "4",
            "F8": "9120",
            "F9": "01",
            "sectionName": "F"
        },
        {
            "G1": "02",
            "G2": "02",
            "G3": "02",
            "sectionName": "G"
        },
        {
            "H10": "Car",
            "sectionName": "H"
        }
    ]
}

我相信一定有天才能够解决我的问题。非常感谢。 欢迎提供任何建议。


你可以使用 reduce 函数。 - junwen-k
如何实现这个?我在JavaScript方面真的很菜,能否给予任何解释? - ameruddin jamil
你可以循环遍历键并将它们添加到一个新对象中,该对象与你的示例一样排序。 - Jerodev
6个回答

8
循环遍历对象的entries,根据键的首字母对它们进行分组。如果组对象已经具有该字母作为键,则更新它。否则,将该字母作为键添加到组对象中。使用Object.values()获取输出所需的answer数组。

const input={answer:{E2:"Tony Stark",E3:"1",E4:"2",E6:"4",E8:"9120",E9:"01",F1:"Marvel",F2:"1",F4:"2",F6:"4",F8:"9120",F9:"01",G1:"02",G2:"02",G3:"02",H10:"Car"}};

const group = {};

for (const [k, v] of Object.entries(input.answer)) {
  const sectionName = k.charAt(0);
  if (group[sectionName])
    group[sectionName][k] = v;
  else
    group[sectionName] = { sectionName, [k]: v };
}

const answer = Object.values(group)

console.log({ answer })


3

像这样遍历answer对象中的条目:

let a =
{
    "answer":
    {
        "E2": "Tony Stark",
        "E3": "1",
        "E4": "2",
        "E6": "4",
        "E8": "9120",
        "E9": "01",
        "F1": "Marvel",
        "F2": "1",
        "F4": "2",
        "F6": "4",
        "F8": "9120",
        "F9": "01",
        "G1": "02",
        "G2": "02",
        "G3": "02",
        "H10": "Car"
    }
};

//map of sections by section name
let m = new Map();
for (let [key, value] of Object.entries(a.answer))
{
  let sectionName = key.charAt(0);
  let section = m.get(sectionName);
  if (!section)
  {
    section =
    {
      sectionName
    };
    m.set(sectionName, section);
  }
  section[key] = value;
}
//create final object
let b =
{
  answer: [...m.entries()].sort(([k1], [k2]) => k1.localeCompare(k2))
               .map(([key, value]) => value)
};
console.log(b);

//map of sections by section name
let m = new Map();
for (let [key, value] of Object.entries(a.answer))
{
  let sectionName = key.charAt(0);
  let section = m.get(sectionName);
  if (!section) {
    section = {
      sectionName
    };
    m.set(sectionName, section);
  }
  section[key] = value;
}
//create final object
let b = {
  answer: [...m.entries()].sort(([k1], [k2]) => k1.localeCompare(k2))
               .map(([key, value]) => value)
};

1
你可以使用哈希表将sectionName和一个对象分组,并仅获取其值作为结果。

var data = { answer: { E2: "Tony Stark", E3: "1", E4: "2", E6: "4", E8: "9120", E9: "01", F1: "Marvel", F2: "1", F4: "2", F6: "4", F8: "9120", F9: "01", G1: "02", G2: "02", G3: "02", H10: "Car" } },
    result = Object.values(Object.entries(data.answer).reduce((r, [k, v]) => {
        var sectionName = k[0];
        r[sectionName] = r[sectionName] || { sectionName };
        r[sectionName][k] = v;
        return r;
    }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


0
希望这能帮到你。

const input = {"answer": { "E2": "Tony Stark", "E3": "1", "E4": "2", "E6": "4", "E8": "9120", "E9": "01", "F1": "Marvel", "F2": "1", "F4": "2", "F6": "4", "F8": "9120", "F9": "01", "G1": "02", "G2": "02", "G3": "02", "H10": "Car" }}

const key_map = {}
const final = {
  answer: []
}
Object.keys(input.answer).map(key => {
  if (!key_map[key[0]]) {
    key_map[key[0]] = {
      "sectionName": key[0]
    }
  }
  key_map[key[0]][key] =input.answer[key]
})

Object.values(key_map).map((v) => {
  final.answer.push(v)
})

console.log(final)


0

const jsonInout = `{
  "answer": {
      "E2": "Tony Stark",
      "E3": "1",
      "E4": "2",
      "E6": "4",
      "E8": "9120",
      "E9": "01",
      "F1": "Marvel",
      "F2": "1",
      "F4": "2",
      "F6": "4",
      "F8": "9120",
      "F9": "01",
      "G1": "02",
      "G2": "02",
      "G3": "02",
      "H10": "Car"
  }
}`;

// Parse response
let obj = JSON.parse(jsonInout, null, 2).answer;

// Get sections
const sections = Array.from(new Set(Object.keys(obj).map(key => {
  return key[0];
})));

// Get splitted object
const splitted = {
  answer: sections.map(sectionKey => {
    let section = { sectionName: sectionKey };
    for (let [key, value] of Object.entries(obj)) {
      if (key[0] === sectionKey) section[key] = value;
    }
    return section;
  })
};

console.log(splitted);


0
应该可以工作
let myObject = {
  'answer': {
    'E2': 'Tony Stark',
    'E3': '1',
    'E4': '2',
    'E6': '4',
    'E8': '9120',
    'E9': '01',
    'F1': 'Marvel',
    'F2': '1',
    'F4': '2',
    'F6': '4',
    'F8': '9120',
    'F9': '01',
    'G1': '02',
    'G2': '02',
    'G3': '02',
    'H10': 'Car'
  }
}
let myResult = []
for (let index in myObject.answer) {
  let sectionName = index.substr(0, 1)
  let indexFound = myResult.findIndex(r => r.sectionName === sectionName)
  if (indexFound >= 0) {
    myResult[indexFound][index] = myObject.answer[index]
  } else {
    myResult.push({ 'sectionName': sectionName })
    myResult[(myResult.length - 1)][index] = myObject.answer[index]
  }
}
console.log({
  answer: myResult
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接