如何在对象内部拆分字符串并将其推入数组?使用Javascript

时间:2017-06-29 09:49:31

标签: javascript arrays object ecmascript-6 react-jsx

我收到一个对象,每次每次不同数量的字符串不同

Home

我想收到

export function onEnter(nextState, transition, callback) {
  const { pathname } = nextState.location
  const isLoggedIn = sessionStorage.getItem('loggedin') === 'true'
  if (pathname === '/login' && isLoggedIn) {
    transition('/') //redirect to Home component
  }
  return callback() // go as it is.
}


class App extends React.Component {

  render() {
    return (
      <Router>
        <div>
          <Nav />
          <Route exact path="/" component={Home} onEnter={onEnter}/>
          <Route exact path="/contact" component={contact} onEnter={onEnter}/>
          <Route path="/login" component={Login} onEnter={onEnter}/>
        </div>
      </Router>
    )
  }
}

Object {
    key_id: 7, 
    key1: "String1, String2", 
    key2: "String1, String2, String3", 
    key3: "String1, String2", 
    key4: "String1, String2";
    …
}

我需要将这些字符串分开,以便从它们分离链接。 我正在使用JSX / Babel ES6

在ReactJs上制作它

2 个答案:

答案 0 :(得分:2)

使用Object#entries转换为[key,value]对数组,并Array#map

&#13;
&#13;
const data = {
  key_id: 7, 
  key1: "String1, String2", 
  key2: "String1, String2, String3", 
  key3: "String1, String2", 
  key4: "String1, String2"
};

const result = Object.entries(data).map(([key, value]) => ({
  [key]: typeof value === 'string' ? value.split(', ') : value
}));

// an array with multiple objects
console.log(result);

// A single object:
console.log(Object.assign({}, ...result));
&#13;
&#13;
&#13;

请注意,Object#entries不是ES6的一部分,IE和Edge不支持。

答案 1 :(得分:0)

编辑:更新了代码,将每个属性更改为数组元素。

&#13;
&#13;
let data = {
  key_id: 7, 
  key1: "String1, String2", 
  key2: "String1, String2, String3", 
  key3: "String1, String2", 
  key4: "String1, String2"
};

Object.keys(data).forEach(function(key) {
    data[key] = typeof data[key] === 'string' ? data[key].split(', ') : data[key];
});

console.log(data);
&#13;
&#13;
&#13;