I have variables here firstName which is Faisal and lastName which is Iraqi.
let str = "Faisal Iraqi";
let [firstName, lastName] = str.split(" ");
console.log(firstName, lastName);
console.log(str.split(" "));
so I should add this properties to my new object using destructuring:
let obj = {};
obj must return firstName: "Faisal", lastName: "Iraqi"
Simply add them to the object:
let obj = {firstName, lastName};
So the whole code looks like:
let str = "Faisal Iraqi";
let [firstName, lastName] = str.split(" ");
let obj = {firstName, lastName};
console.log(obj);
Instead of using a destructuring assignment as you create new variables, you can directly destructure into the object properties:
let str = "Faisal Iraqi";
let obj = {};
[obj.firstName, obj.lastName] = str.split(" ");
console.log(obj);
Related
The result is returning {firstname: 'Mike,Henry,Pete', lastname: 'Port,Split,Micky'}
I want result to return
{
firstName: Mike,
lastName: Port
},
{
firstName: Henry,
lastName: Split
},
{
firstName: Pete,
lastName: Micky
}
var data = "Mike Port, Henry Split, Pete Micky";
var firstName = [];
var lastName = [];
var result = [];
var newNames = data.replaceAll(", ", ",");
var fullName = newNames.split(',');
fullName.forEach(name => {
let splitted = name.split(" ");
firstName.push(splitted[0]);
lastName.push(splitted[1]);
});
f_name_list = firstName.toString().split(", ");
l_name_list = lastName.toString().split(", ");
for (let i = 0; i < f_name_list.length; i++) {
result.push({
firstname: f_name_list[i],
lastname: l_name_list[i]
});
}
console.log(result);
split data with ", " then split with " "
var data = "Mike Port, Henry Split, Pete Micky";
var result = [];
var newNames = data.split(", ");
newNames.forEach(name => {
let splitted = name.split(" ");
result.push({
firstname:splitted[0],
lastname: splitted[1]
});
});
console.log(result);
You can do in one line combining String#split() with Array#map() and Destructuring assignment
Code:
const data = 'Mike Port, Henry Split, Pete Micky'
const result = data
.split(', ')
.map(s => s.split(' '))
.map(([firstname, lastname]) => ({ firstname, lastname }))
console.log(result)
In the long-term it maybe better to not specify the keys in the code. What if you were to add a new property called age to the data? That would mean having to go into into the code and update it to accommodate the change which is a hassle.
This example removes that complication by keeping a track of the keys, and looping over them, and the values, to create a new dataset. No hard-coding of the keys anywhere.
const data = {
firstname: 'Mike,Henry,Pete',
lastname: 'Port,Split,Micky',
age: '10,100,20',
location: 'France,Germany,Iceland',
role: 'chef,musician,writer',
tree: 'larch,maple,oak'
};
// Get the keys and values from the object
const keys = Object.keys(data);
const values = Object.values(data).map(str => str.split(','));
// Temporary array
const out = [];
// Loop over the first array in the values array
for (let i = 0; i < values[0].length; i++) {
// Initialise an empty object
// for each nested array
const obj = {};
// Loop over the keys, create a new object with
// that key, and the element of the nested value array
// and merge it with the object
for (let j = 0; j < keys.length; j++) {
const prop = { [keys[j]]: values[j][i] };
Object.assign(obj, prop);
}
// Push the object to the array
out.push(obj);
}
console.log(out);
Additional documentation
Object.keys
Object.keys
Object.assign
Here is the code:
var data = "Mike Port, Henry Split, Pete Micky";
function parseData(data){
data = data.split(', ')
let arr = []
for(i=0;i<data.length;i++){
arr.push({firstName:data[i].split(' ')[0].replace(',',''),lastName:data[i].split(' ')[1]})
}
return arr
}
console.log(parseData(data))
I have the following string:
myString = "Name:Joe Email:info#domian.com Details: I like Sushi";
I would like to split it out into separate variables like:
name = "Joe";
email = "info#domian.com";
details = "I like Sushi";
I tried something like the below, but it didn't account for everything.
myString = "Name:Joe Email:info#domian.com Details: I like Sushi";
splitString = myString.split(':');
myName = splitString[1];
myEmail = splitString[2];
myFood = splitString[3];
console.log('Name: ', myName);
console.log('Email: ', myEmail);
console.log('Food: ', myFood);
I'm wondering if there might be a creative way to do this in JS? Thanks.
This will turn your string into an object with key/value pairs using match() and split(). You can then access the variables using the object, like obj.name or obj.email. There may be a way to fix my regex so that the .shift() method isn't necessary, but it works nonetheless.
let myString = "Name:Joe Email:info#domian.com Details: I like Sushi";
let keys = myString.match(/\w+:/g)
let values = myString.split(/\w+:/);
values.shift(); // remove first item which is empty
let obj = {};
keys.forEach((key, index) => {
obj[key.replace(":", "").toLowerCase()] = values[index].trim()
})
console.log(obj)
// access variables like obj.name or obj.email
Try this:
myString = "Name:Joe Email:info#domian.com Details: I like Sushi";
splitString = myString.split(':');
myName = splitString[1].split(' ')[0];
myEmail = splitString[2].split(' ')[0];
myFood = splitString[3]
console.log(myName);
console.log(myEmail);
console.log(myFood);
If you want to get rid of the space in front of "I like Sushi":
details = splitString[3].split(' ');
myDetails = details[1] +' '+ details[2] +' '+ details[3]; console.log(myDetails);
var myString = "Name:Joe Email:info#domian.com Details: I like Sushi";
var arr = myString.replace(/:\s/g, ':').split(" "),
obj = {};
// .replace(/:\s/g,':') Or .replace(/[:\s]/g,':') whichever works better
for (var i = 0; i < arr.length; i++) {
var item = arr[i],
arr2 = item.split(":"),
key = arr2[0].toLowerCase();
obj[key] = arr2[1];
}
console.log(obj["email"]);
//info#domain.com
console.log(obj["details"]);
//I like Sushi
Is there any better way to implement this?
const a = _.get(obj, 'property');
const b = a ? [a] : [];
obj is an object, may or may not have property. If it does, return an array of one element of property, else return an empty array.
const obj = {
prop: "hello"
}
const b = obj.hasOwnProperty("prop") ? [obj.prop] : [];
let obj = {}
console.log("when property is not present: ", obj["property"] || [])
obj = {property: ["hello"]}
console.log("when property is present: ", obj["property"] || [])
You could wrap it into array an filter non-nil value
const a = _.get(obj, 'property');
const b = [a].filter(Boolean);
const a1 = null
const a2 = 1
const res1 = [a1].filter(Boolean)
const res2 = [a2].filter(Boolean)
console.log(res1)
console.log(res2)
I have the following exercise:
Write a function called createListOfObjects that accepts an
an array of strings with first and last names and returns
an array of objects that each have the property firstName
and lastName and first name and last name values
corresponding value
*
var namesList = ['Cameron Betts', 'Shana Lopez', 'Angela Li']
*
createListOfObjects(namesList)
=>
[
{ firstName: 'Camer', lastName: 'Betts'},
{ firstName: 'Shana', lastName: 'Lopez'},
{ firstName: 'Angela', lastName: 'Li'}
]
And my solution until now:
createListOfObjects = () => {
let names = ['Cameron Betts', 'Shana Lopez', 'Angela Li'];
let deck = [];
for (var i=0; i < names.length; i++){
for (var k=0; k < names.length; k++){
deck.push({ fName: names[i], lName: names[k]})
}
};
return deck;
}
console.log(createListOfObjects());
But it returns the following:
I have to extract the names from the array and then split them to use in my for but I can't understand how exactly I can do that.
One option would be to split each full name, so as to have the first and last name, and then you can create an object from those two variables. Ideally, use .map for this - .map is the most appropriate method for transforming every element in one array into another array:
createListOfObjects = names => names.map((name) => {
const [firstName, lastName] = name.split(' ');
return { firstName, lastName };
});
console.log(createListOfObjects(['Cameron Betts', 'Shana Lopez', 'Angela Li']));
To fix your existing code, you would need to iterate over names only once (no nested loops), and on each iteration, split the name string, and push to deck:
const createListOfObjects = () => {
let names = ['Cameron Betts', 'Shana Lopez', 'Angela Li'];
let deck = [];
for (var i=0; i < names.length; i++){
const fullName = names[i];
const nameArray = names[i].split(' ');
const fName = nameArray[0];
const lName = nameArray[1];
for (var k=0; k < names.length; k++){
deck.push({ fName, lName });
}
}
return deck;
}
console.log(createListOfObjects());
Split the array items to give first and last names and then reutn a new array with each being passed as an object. Note that if an objects key is the same name as a viariable - you don't need to state it.
var namesList = ['Cameron Betts', 'Shana Lopez', 'Angela Li'] ;
createListOfObjects(namesList);
function createListOfObjects(arr) {
let newArr = [];
arr.forEach(function(name){
var namePortions = name.split(' ');
var firstName = namePortions[0];
var lastName = namePortions[1];
newArr.push ({firstName, lastName});
})
console.log(newArr);
}
You're not splitting the name string on the space, to separate the first and last names.
Also, for every name, you're iterating over every name.
meaning that if you were splitting the name right, you would end up with every first name coupled with every last name.
What you want is to:
create variable with empty array deckArray.
iterate over fullNamesArray
forEach fullNameString
split the fullNameString on the space character
to get a tuple (array of two) with [firstName, lastName]
store firstName and lastName into nameObject
push nameObject into deckArray
return deckArray
like so
const createListOfObjects = (names) => {
let deck = [];
for(let i = 0; i < names.length; i += 1) {
let [ firstName, LastName ] = names[i].split(' ');
deck.push({ firstName, lastName });
}
return deck;
}
const names = ['Cameron Betts', 'Shana Lopez', 'Angela Li'];
createListOfObjects(names);
better with map
const createListOfObjects = (names) => names.map((fullName) => {
let [ firstName, lastName ] = fullName.split(' ');
return { firstName, lastName };
});
let string = 'My name is [~FIRSTNAME] [~LASTNAME]';
let nameArray = ['Peter', 'Parker'];
let patternToBeReplaced = ['[~FIRSTNAME]', '[~LASTNAME]']
I want to replace the string with the elements of namearray so that the string becomes 'My name is Peter Parker'
Below is my approach to this problem -
patternToBeReplaced.forEach(function (match, index) {
var output = string.replace(match, nameArray[index]);
});
But this is not working as expected.
You could use Array#reduce and use the string for the next replacement.
let string = 'My name is [~FIRSTNAME] [~LASTNAME]';
let nameArray = ['Peter', 'Parker'];
let patternToBeReplaced = ['[~FIRSTNAME]', '[~LASTNAME]']
string = patternToBeReplaced.reduce((s, m, i) => s.replace(m, nameArray[i]), string);
console.log(string);
You're creating a string templating system. Since you're using ECAMScript 6 syntax already, you could use the new built-in template literals.
let [FIRSTNAME, LASTNAME] = ['Peter', 'Parker'];
let string = `My name is ${FIRSTNAME} ${LASTNAME}`;
console.log(string);
This will also work more cleanly when there are multiple insertions of a given label within the string.
let [FIRSTNAME, LASTNAME] = ['Peter', 'Parker'];
let string = `My name is ${LASTNAME}... ${FIRSTNAME} ${LASTNAME}`;
console.log(string);
patternToBeReplaced.forEach(function (match, index) {
string = string.replace(match, nameArray[index]);
});
Something like that.
let str = 'My name is [~FIRSTNAME] [~LASTNAME]';
let nameArray = ['Peter', 'Parker'];
let patternToBeReplaced = ['[~FIRSTNAME]', '[~LASTNAME]']
const result = patternToBeReplaced.reduce((str, placeholder, i) => {
return str.replace(placeholder, nameArray[i]);
}, str);
console.log(result);
output is a local variable, it's useless to just declaring it.
replace(String, String) would only replace the first matched pattern.
Here's my solution:
let replaceWithArrayElements = (patterns, replacements, targetString) => {
patterns.forEach((pattern, i) => targetString = targetString.replace(new RegExp(pattern, 'g')));
return targetString;
}
First solution, keeping your base code :
let string = 'My name is [~FIRSTNAME] [~LASTNAME]';
let nameArray = ['Peter', 'Parker'];
let patternToBeReplaced = ['[~FIRSTNAME]', '[~LASTNAME]'];
patternToBeReplaced
.forEach((match, i)=>{
string = string
.replace(match, nameArray[i]);
});
Using Map:
let string = 'My name is [~FIRSTNAME] [~LASTNAME]';
let replaceMap = new Map();
replaceMap.set('[~FIRSTNAME]', 'Peter');
replaceMap.set('[~LASTNAME]', 'Parker');
replaceMap.forEach((key, value)=>{
string = string.replace(key, value);
});
Using ES6 "template" strings:
/*
*Have some ways of getting the first name in "firstName"
*Have some ways of getting the last name in "lastName"
*/
let string = `My name is ${firstName} ${lastName}`;
string.match(/\[~\w+\]/g).forEach((item,index)=>{
string = string.replace(item, nameArray [index])
})
You can use the above code for you needs