我收到一个对象,每次每次不同数量的字符串不同
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上制作它答案 0 :(得分:2)
使用Object#entries
转换为[key,value]对数组,并Array#map
:
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;
请注意,Object#entries
不是ES6的一部分,IE和Edge不支持。
答案 1 :(得分:0)
编辑:更新了代码,将每个属性更改为数组元素。
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;