如果值包含逗号,则循环并将对象字符串值转换为对象

时间:2019-05-19 22:29:20

标签: javascript arrays object

我有一个对象:

{x: '1', y: '1,2,3'}

我想遍历它,并将字符串转换为包含逗号的对象。

预期结果应该是:

{x: 1, y: {0: 1, 1: 2, 2: 3}}

我尝试使用Object.entriesmap作为。下面,但我得到的所有结果都不确定。

Object.entries(oResult).map(el => {
  if(el[1].includes(',')) {
    const aEl = el[1].split(',');
    el[1] = Object.assign({}, aEl);
  }
})

4 个答案:

答案 0 :(得分:1)

我认为这可能是您想要的:

const data = {x: '1', y: '1,2,3', z: '4,5,6'};

function transform( object ) {
  let index = 0;

  for ( const key in object ) {
    if ( object[ key ].includes( "," ) ) {
      const splitValues = object[ key ].split( "," ) // get object values into array

      object[ key ] = {}; // create an empty object to add the key/value pairs to
      for ( const value of splitValues ) {
        object[ key ][ index ] = value;
        index++
      }

      index = 0; // reset index for next iteration
    }
  }

  return object;
}

console.log( transform( data ) );

答案 1 :(得分:1)

您可以执行以下操作:

let obj = {x: '1', y: '1,2,3'},
    strToObj = str => str.split(',').reduce((r,c,i) => (r[i] = c, r), {})

let result = Object.entries(obj)
  .reduce((r,[k,v]) => (r[k] = v.includes(',') ? strToObj(v) : v, r), {})

console.log(result)

这个想法是使用Array.reduce通过首先在,上分割字符串来将字符串转换为对象(这是strToObj函数的作用)。然后使用Object.entries,您只需获取键/值并组成最终对象。

您也可以将其作为这样的函数:

let strToObj = str => str.split(',').reduce((r,c,i) => (r[i] = c, r), {})

let convertObject = obj => Object.entries(obj).reduce((r,[k,v]) => 
    (r[k] = v.length < 2 ? v : strToObj(v), r), {})
	
console.log(convertObject({x: '1', y: '1,2,3'}))
console.log(convertObject({x: 'A,BC,D', y: 'D,DD,DDD'}))

答案 2 :(得分:1)

const yourObject = {x: '1234,1235,1236', y: '1,2,3'};
const res = {};

for (let [key, val] of Object.entries(yourObject)) {
  let split = val.split(',').map(s => parseInt(s));
  split.length > 1 ? res[key] = { ...split
  } : res[key] = split[0];
}

console.log(res)

答案 3 :(得分:1)

我们可以使用Object.fromEntriesObject.fromEntries轻松地转换对象-

const transform = (o = {}) =>
  Object.fromEntries(Object.entries(o).map(([k,v]) =>
    [ k
    , v.includes(',')
        ? Object.fromEntries(v.split(',').map((x, i) => [ i, x ]))
        : v
    ]
  ))

console.log(transform({ x: '1', y: '1,2,3' }))
// { x: 1, y: { 0: '1', 1: '2', 2: '3' } }

console.log(transform({ a: 'apple,pear,cherry', b: 'foo,bar' }))
// { a: { 0: 'apple', 1: 'pear', 2: 'cherry' }, b: { 0: 'foo', 1: 'bar' } }