对嵌套对象进行Join(';')

时间:2019-06-28 13:28:30

标签: javascript object ecmascript-6

我正在尝试将一个对象的所有值连接到半冒号分隔符,如果该对象只是一个级别,则可以正常工作:

obj = { 
    name: "one"
    additionalInfo: "hello"
    ...
};

Object.values(obj).join(';')

结果:一个;你好

但是如果对象是嵌套的:

obj = { 
    name: "one"
    additionalInfo: {
         description: "hello",
         ...
    }
};

Object.values(obj).join(';')

结果:一个; [object Object]

除名称外的其余值当然是[object Object]。我如何也可以加入2级值?

我想要的结果是:

one;hello

8 个答案:

答案 0 :(得分:1)

您可以使用递归函数并遍历所有属性,如下所示:

var obj = { 
    name: "one",
    additionalInfo: {
         description: "hello",
    }
};
var val = [];
function getValue(obj){
  for (var property in obj) {
    if (obj.hasOwnProperty(property)) {
      if (typeof obj[property] == "object") {
        getValue(obj[property]);
      } else {
        val.push(obj[property]);          
      }
    }
  }
  return val.join(';');
}
var r = getValue(obj);

console.log(r)

答案 1 :(得分:1)

您可以采用递归方法,方法是在连接对象整个级别的值之前确保转换任何嵌套对象:

function joinObjectValues(obj, delimiter = ";") {
  return Object.values(obj)
    .map(val => {
      //convert any objects recursively
      if (typeof val === "object") {
        return joinObjectValues(val, delimiter);
      }

      return val;
    })
    .join(delimiter)
}

let objOneLevel = {
  name: "one"
};

let objTwoLevels = {
  name: "one",
  additionalInfo: {
    description: "hello",
  }
};

let objThreeLevels = {
  name: "one",
  additionalInfo: {
    description: "hello",
    other: {
      customField: "world"
    }
  }
};


console.log(joinObjectValues(objOneLevel))
console.log(joinObjectValues(objTwoLevels))
console.log(joinObjectValues(objThreeLevels))

答案 2 :(得分:1)

对于一个以上的级别,您可以执行以下操作:

var obj = { 
    name: "one",
    additionalInfo: {
         description: "hello",
         yes : 'world'
    }
};

function join(obj) {
  var arr = [];
  for(let key in obj) {
       typeof obj[key] == 'object'? arr.push(Object.values(obj[key])):arr.push(obj[key])
  }
  return arr.join(';')
}


console.log(join(obj))

答案 3 :(得分:1)

要获得预期结果,请使用以下将对象更改为字符串的选项,并使用}

查找值
  1. 使用 JSON.stringify 将obj更改为字符串,并用“
  2. 进行拆分
  3. 获取“ ”和“ 之间的单词,并关闭“ ”和“ }”之间的单词
  4. 使用repalce删除不需要的字符

工作代码示例,并添加了一些其他对象进行测试

obj = { 
    name: "one",
    additionalInfo: {
         description: "hello",
    },
    test: "abc",
    grandparent: {
      parent: {
        child: "child"
      }
    }
};

function concatObj(obj){
  let str = JSON.stringify(obj).split(":");
  return str.map(v => v.substr(0, v.indexOf(",")) || v.substr(0, v.indexOf("}"))).filter(Boolean).join(":").replace(/"|}|{/g,'')  
}

console.log(concatObj(obj))

codepen-https://codepen.io/nagasai/pen/pXpwdM?editors=1010

答案 4 :(得分:0)

const obj = { 
  name: 'one',
  additionalInfo: {
    description: 'hello',
    sacri: ['m', 'e', 'n', 't', 'o'],
    foo: {
      bar: 'bat',
      biz: {
        tik: 'tock',
        hello: {
          world: 'YO',
          number: 5,
          bools: {
          	positive: true,
            negative: false,
            funcs: {
            	do: () => console.log('hello')
            }
          }
        }
      }
    }
  }
}

const stripObj = obj => (
  Object.values(obj)
  .reduce((prev, curr) => typeof curr === 'object' ? [...prev, stripObj(curr)] : [...prev, curr], [])
  .join(';')
)

const res = stripObj(obj)

console.log(res);

答案 5 :(得分:0)

Caused by: org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:mergeReleaseResources'

...


drawable-mdpi-v4/assets_images_swedenicon] /home/kacey/timeme-app-new/TimeMe/android/app/build/generated/res/react/release/drawable-mdpi/assets_images_swedenicon.png   [drawable-mdpi-v4/assets_images_swedenicon] /home/kacey/timeme-app-new/TimeMe/android/app/src/main/res/drawable-mdpi/assets_images_swedenicon.png: Error: Duplicate resources
[drawable-mdpi-v4/asset

答案 6 :(得分:0)

使用递归函数吗?

const obj = {
  name: "one",
  additionalInfo: {
    description: "hello",
  }
};


const mapped = flatObject(obj).flat().join(';')

console.log(mapped)


// this is a recursive function
function flatObject(obj) {
  const ret = []
  for (let val in Object.values(obj)) {
    if (typeof Object.values(obj)[val] !== 'string') {
      ret.push(flatObject(Object.values(obj)[val]))
    } else {
      ret.push(Object.values(obj)[val])
    }
  }
  return ret
}

答案 7 :(得分:0)

使用递归-

let objValues = [];
    function getObjValues(obj) {
        const objValuesArray = Object.values(obj);
        objValuesArray.forEach((objVal) => {
            if(typeof objVal === 'object') {
                getObjValues(objVal);
            } else {
                 objValues.push(objVal);
            }
        });
      return objValues.join(';');
    }

  const obj = {
            name: "one",
            additionalInfo: "hello",
            newObject: {
                newname: "two",
                info: "news"
            }
        }; 

const concatenatedValues = getObjValues(obj);
console.log(concatenatedValues);