Reputation: 1427
I'm new to JavaScript. I have the following object:
let obj1 =
[{
'id': 1,
'longString': 'Joe - 2011-04-23T18:25:23.511Z'
},
{
'id': 2,
'longString': 'Mary - 2010-04-23T18:25:23.511Z'
}];
I want to split the longString
key into 2 keys, and the value into 2 values.
Here is what I want to make:
let obj2 =
[{
'id': 1,
'name': 'Joe',
'date': '2011-04-23T18:25:23.511Z'
},
{
'id': 2,
'name': 'Mary',
'date': '2010-04-23T18:25:23.511Z'
}];
I've tried to do it in pieces, but I'm stuck with the first piece which is splitting the value of longString
.
This works for string:
let v = 'Mary - 2010-04-23T18:25:23.511Z';
let w = v.split(' -', 1);
How do I make it work for an object? Or is there a totally different way to split property values? Also, do I need to write a loop to assign obj1
to obj2
?
Upvotes: 2
Views: 873
Reputation: 3721
let obj1 = [{
'id': 1,
'longString': 'Joe - 2011-04-23T18:25:23.511Z'
},
{
'id': 2,
'longString': 'Mary - 2010-04-23T18:25:23.511Z'
}
];
const res = obj1.map(({
id,
longString
}) => ({
id,
name: longString.match(/\w+/)[0],
date: longString.match(/\d+.*/)[0],
}))
console.log(res)
Upvotes: -1
Reputation: 35222
You could map
over the array and split the longString
for each object. Use destructuring to get the splits into name
and date
variables
let obj1 =
[{
'id': 1,
'longString': 'Joe - 2011-04-23T18:25:23.511Z'
},
{
'id': 2,
'longString': 'Mary - 2010-04-23T18:25:23.511Z'
}];
const output = obj1.map(a => {
let [name, date] = a.longString.split(" - ");
return { id: a.id, name, date }
})
console.log(output)
Upvotes: 4
Reputation: 37755
You can simply use map
and \s+-\s+
pattern to split. second parameter of split is to specify the number of element we want in output
let obj1 =[{'id': 1,'longString': 'Joe - 2011-04-23T18:25:23.511Z'},{ 'id': 2, 'longString': 'Mary - 2010-04-23T18:25:23.511Z'}];
let op = obj1.map(({id, longString}) => {
let [name, date] = longString.split(/\s+-\s+/,2)
return { id, name, date }
})
console.log(op)
Upvotes: 2