展平对象数组时遇到麻烦

时间:2019-07-15 19:58:14

标签: javascript

我正在尝试通过将具有多个属性的内部对象转换为字符串来减少对象的数组,然后用该字符串替换对象的内容,并使用delete关键字删除该属性,并然后添加一个具有相同名称的字符串属性。由于某种原因,在删除某些属性后,我的代码仍在该属性上运行,但是现在它是字符串,而不是对象,并且代码崩溃。例如下一个对象:

    var person={
                id:2, 
                userNames:[{name:"jack1", email:"jack1@ccc.com"}, 
                           {name:"superjack", email:"superjack@bbb.com"}],
                empryProp:"",
                empryArr:[],
                booleanProp:true
               }

最终目标是将此对象平整为:

    var person={
                id:2, 
                userNames:"jack1 jack1@ccc.com; superjack superjack@bbb.com",
                empryProp:"",
                empryArr:[],
                booleanProp:true
               }

JS:

    function flattenArrOfObjects(arrayOfObj){

    let tmpVa = "";
    let tmpProp = "";

    arrayOfObj.forEach(avatarObj => {
        for(let avatarProp in avatarObj){
            if (avatarProp === "dateCreated" || avatarProp === "dateModified") {
                avatarObj[avatarProp] = new Date(avatarObj[avatarProp]).toLocaleDateString();
                continue;
              }

              if(avatarObj[avatarProp].length === 0 ||
                 avatarObj[avatarProp] === "" || 
                 avatarObj[avatarProp] === 0 || 
                 typeof(avatarObj[avatarProp])=== "boolean" ||
                 typeof avatarObj[avatarProp] === "number"){
                  continue;
              }else{
                //lets decide what avatarProp is. single string? array of strings? array of objects?
                if(Array.isArray(avatarObj[avatarProp])){
                    //its an array. strings or objects?
                    avatarObj[avatarProp].forEach(element => {
                        if(typeof(element) === "object"){
                            //its an array of objects
                            avatarObj[avatarProp].forEach(obj => {
                                tmpProp = avatarProp;
                                for(let avatarProp in obj){
                                    if(avatarProp === "dateCreated" || avatarProp === "dateModified" || avatarProp === "id"){
                                        continue;
                                    }else{
                                        tmpVa += avatarProp + " - " + obj[avatarProp]+"; ";
                                    }
                                }
                            });
                            delete avatarObj[tmpProp];
                            avatarObj[tmpProp] = tmpVa;
                            tmpProp = "";
                            tmpVa = "";
                        }else{
                            //array of strings
                            avatarObj[avatarProp] = avatarObj[avatarProp].join("; ");
                        }
                    });
                }
              }
        }
    });

    return arrayOfObj;
  }

$('button').on('click', function() {
  function flattenArrOfObjects(arrayOfObj) {

    let tmpVa = "";
    let tmpProp = "";

    arrayOfObj.forEach(avatarObj => {
      for (let avatarProp in avatarObj) {
        if (avatarProp === "dateCreated" || avatarProp === "dateModified") {
          avatarObj[avatarProp] = new Date(avatarObj[avatarProp]).toLocaleDateString();
          continue;
        }

        if (avatarObj[avatarProp].length === 0 ||
          avatarObj[avatarProp] === "" ||
          avatarObj[avatarProp] === 0 ||
          typeof(avatarObj[avatarProp]) === "boolean" ||
          typeof avatarObj[avatarProp] === "number") {
          continue;
        } else {
          //lets decide what avatarProp is. single string? array of strings? array of objects?
          if (Array.isArray(avatarObj[avatarProp])) {
            //its an array. strings or objects?
            avatarObj[avatarProp].forEach(element => {
              if (typeof(element) === "object") {
                //its an array of objects
                avatarObj[avatarProp].forEach(obj => {
                  tmpProp = avatarProp;
                  for (let avatarProp in obj) {
                    if (avatarProp === "dateCreated" || avatarProp === "dateModified" || avatarProp === "id") {
                      continue;
                    } else {
                      tmpVa += avatarProp + " - " + obj[avatarProp] + "; ";
                    }
                  }
                });
                delete avatarObj[tmpProp];
                avatarObj[tmpProp] = tmpVa;
                tmpProp = "";
                tmpVa = "";
              } else {
                //array of strings
                avatarObj[avatarProp] = avatarObj[avatarProp].join("; ");
              }
            });
          }
        }
      }
    });




    return arrayOfObj;
  }

  var personObj = [{
    accounts: [],
    addresses: [{
      country: "spain",
      city: "madrid",
      street: "someStreet",
      number: 44
    }],
    age: 44,
    country: "spain",
    dateCreated: "2019-06-19T16:09:24.73",
    dateModified: "2019-07-15T12:15:34.94",
    description: "some description",
    device: 0,
    education: [{
      school: "saint charles",
      degree: "master",
      id: 3,
      dateCreated: "2019-06-19T16:09:24.73"
    }, {
      school: "saint clair",
      degree: "not finished",
      id: 2,
      dateCreated: "2018-06-19T16:09:24.73"
    }],
    emails: [{
      dateCreated: "2019-06-19T16:09:24.73",
      mail: "mymail@kkk.com"
    }, {
      dateCreated: "2015-06-19T16:09:24.73",
      mail: "dddddd@kkk.com"
    }],
    favorites: [],
    gender: 2,
    id: 23,
    images: [],
    tab: false,
    interests: ["pet cats", "i love to throw eggplants"],
    isActive: true,
    languages: [{
      language: "english",
      isDefault: true
    }, {
      language: "spanish",
      isDefault: false
    }],
    reports: [],
    maritalStatus: 0,
    name: "Sienna",
    names: [{
      name: "Sienna",
      isDefault: true
    }, {
      language: "Marel",
      isDefault: false
    }],
    nicknames: [],
    phoneNumbers: [{
      language: "english",
      isDefault: true
    }, {
      language: "spanish",
      isDefault: false
    }],
    pictureUrl: "/clientapp/images/blanks/p_profile icon_large_dark.png",
    politicalOrientation: "",
    userAgent: "",
    workPlaces: [{
      company: "apple",
      job: "chairman"
    }, {
      company: "intel",
      job: "lab worker"
    }]
  }];
  console.log(flattenArrOfObjects(personObj));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>flat objects</button>

2 个答案:

答案 0 :(得分:1)

q    t    q'   t'   d      comment

q0   0    q0   0    right  see a zero, stay in state and keep looking
q0   1    q1   1    right  see a one, now we've seen odd number, keep looking
q0   B    ha   0    same   ran out after seeing even number

q1   0    q1   0    right  see a zero, stay in state and keep looking
q1   1    q0   1    right  see a one, now we've seen an even number, keep looking
q1   B    hA   1    same   ran out after seeing odd number

const person = { id: 2, userNames: [{ name: "jack1", email: "jack1@ccc.com" }, { name: "superjack", email: "superjack@bbb.com" }], empryProp: "", empryArr: [], booleanProp: true } const flatPerson = person =>({ ...person, userNames: person.userNames.map(user => `${user.name} ${user.email}`).join('; ') }) console.log(flatPerson(person))是一个函数,它接受一个flatPerson参数,然后返回一个对象,该对象是原始人对象person的扩展,并且覆盖了...person属性,从而进行了转换将每个对象转换成字符串:userNames $ {user.name} $ {user.email} userNames.map(user =>,然后将最终数组转换为字符串,并将分隔符传递为:)

答案 1 :(得分:0)

最终遍历所有对象及其键,过滤掉不需要的属性,另一方面从我需要的属性中创建字符串。

function flat(arrayOfExportedObjects) {
    arrayOfExportedObjects.forEach(exportedObj => {
        for (let prop in exportedObj) {
            if (typeof exportedObj[prop] !== "string" && typeof exportedObj[prop] !== "number" && exportedObj[prop].length > 0) {
                if(Array.isArray(exportedObj[prop]) && typeof(exportedObj[prop][0]) === "string"){
                    exportedObj[prop] = exportedObj[prop].join("; ");
                    continue;
                }
                let str="";
                for(let p=0; p < exportedObj[prop].length; p++){
                    for(let property in  exportedObj[prop][p]){
                        if(property === "dateCreated" || property === "dateModified" || property === "id" || property === "isDefault"){
                            continue;
                        }else{
                            str += exportedObj[prop][p][property]+ " ";
                        }
                    }
                    str +="; ";
                }
                exportedObj[prop] = str;
                str="";
            }else{
                if(exportedObj[prop].length === 0 || exportedObj[prop] === "" || !exportedObj[prop]){
                    exportedObj[prop]=" ";
                }
            }
        }
    });
    return arrayOfExportedObjects;
}