将单个对象拆分为多个对象

时间:2018-11-20 18:39:38

标签: javascript arrays ecmascript-6 ecmascript-5 m

我有一个JSON对象,我想将其拆分为多个对象。我尝试将单个JSON对象转换为数组。如果没有密钥,即进餐1,进餐2等,我无法弄清楚将单个对象分解的模式。我什至不确定这是否是最好的方法。我感谢任何帮助或朝着正确方向的指点!

之前

{
  "fullName1" : "John Doe",
  "attendance1" : 1,
  "meal1" : "salmon",
  "fullName2" : "Jane Doe",
  "attendance2" : 0
}

所需结果

{
  "fullName" : "John Doe",
  "attendance" : 1,
  "meal" : "salmon"
},
{
  "fullName" : "Jane Doe"
  "attendance" : 0
}

就我的尝试而言,这是我所走的距离:

const entries = [...elements];
// check for valid elements
const isValidElement = element => {
  return element.name && element.value;
};
const isValidValue = element => {
  return (!['radio'].includes(element.type) || element.checked);
};
const formToJSON = elements =>
  [].reduce.call(elements, (data, element) => {
    if (isValidElement(element) && isValidValue(element)) {
      data[element.name] = element.value;
    }
    return data;
  }, {});
//
const singleArray = formToJSON(entries);

3 个答案:

答案 0 :(得分:0)

在不知道会有多少个对象的情况下,最好将它们拆分为对象数组。首先遍历键,然后检查其索引。假定键总是以数字结尾,并且结尾的数字始终是索引。

var obj = {
  "fullName1" : "John Doe",
  "attendance1" : 1,
  "meal1" : "salmon",
  "fullName2" : "Jane Doe",
  "attendance2" : 0
};
var objs = [];
Object.keys(obj).forEach(function(key) {
  var match = key.match(/(.*)(\d.*)$/);
  var newKey = match[1];
  var index = parseInt(match[2]) - 1;
  objs[index] = objs[index] || {};
  objs[index][newKey] = obj[key];
})
console.log(objs);

答案 1 :(得分:0)

您可以像下面那样使用Object.entriesreduce来实现这一目标

遍历对象中的每条记录,并将键中的最后数字存储在临时对象中。

let obj = {
  "fullName1" : "John Doe",
  "attendance1" : 1,
  "meal1" : "salmon",
  "fullName2" : "Jane Doe",
  "attendance2" : 0
}

let res = Object.entries(obj).reduce((o, [k, v]) => {
    let [name, number] = k.match(/\D+|\d+$/g)
    o[number] = { ...(o[number] || {}), [name]: v }
    return o
  }, {})
  
console.log(Object.values(res))

答案 2 :(得分:0)

这里如何分成三个相等的块

const splitIntoThreeChunks = (obj) => {
    let obj1 = {}
    let obj2 = {}
    let obj3 = {}

    const keys = Object.keys(obj)
    const keysLength = keys.length
    let k = 0

    for (let i = 0; i <= keysLength; i++) {
        const key = keys[i]
        if (k === 0) {
            obj1 = { ...obj1, [key]: obj[key] }
            k++
        } else if (k === 1) {
            obj2 = { ...obj2, [key]: obj[key] }
            k++
        } else if (k === 2) {
            obj3 = { ...obj3, [key]: obj[key] }
            k = 0
        }
    }

    return {
        obj1,
        obj2,
        obj3
    }
}