say I have
type Person = {
name: string
hobbies: Array<string>
}
and then this: const people: Array<Person> = [{name: "rich", age: 28}]
how do I add age AND replace hobbies with say a different type (Array<number>) to keep it simple
I know I can use omit to get rid of a property or intersections to add a property but I'm struggling to work it out
Obviously this is wrong but I want something like that
type Hobbies = Array<number>
type NewPerson = Omit<Person, "hobbies"> & Hobbies & Age
const people: Array<NewPerson> = [{name: "rich", age: 28, hobbies: [1,2,3]}]
You neet to intersect with object types that have the extra properties you want to add
type Hobbies = { numbers: Array<number>}
type NewPerson = Omit<Person, "hobbies"> & Hobbies & { age: number }
const people: Array<NewPerson> = [{name: "rich", age: 28, numbers: [1,2,3]}]
Playground Link
Maybe the example below helps.
type NewPerson = Omit<Person, "hobbies"> & { hobbies: Array<number>, age: number }
const people: Array<NewPerson> = [{name: "rich", age: 28, hobbies: [1, 2, 3]}]
Use the Omit type to remove the hobbies property from the Person type and then add in the new hobbies and age properties.
You're right you'd use Omit and an intersection. To remove hobbies and add age you'd do Omit and intersect with an object type defining age and the new version of hobbies:
type Person = {
name: string;
hobbies: Array<string>;
};
type NewPerson = Omit<Person, "hobbies"> & { age: number, hobbies: number[] };
const people: Array<NewPerson> = [{ name: "rich", age: 28, hobbies: [1,2,3] }];
Playground link
Related
Let's assume I'm obtaining an array of objects from a Node Repository, for example:
results = [
{
name: "John",
surname: "Fool",
age: 22
},
{
name: "Erik",
surname: "Owl",
age: 38
}
]
How can I filter every object taking only the keys I need, for example avoiding 'age' key?
filteredResults = [
{
name: "John",
surname: "Fool",
},
{
name: "Erik",
surname: "Owl",
}
]
I've already obtained this by creating another empty array and populating it by looping on the original one, but in case of large-data this would be heavy.
repository.retrieve((error, result) => {
let filteredData = [];
result.forEach(r => {
filteredData.push({
name: r.name,
description: r.description,
});
});
});
In SQL, I would obtain it this way:
SELECT `name, description` FROM results;
You can just rebuild the object as you want
{
name: rec.name,
surname: rec.surname
}
const results = [
{
name: "John",
surname: "Fool",
age: 22
},
{
name: "Erik",
surname: "Owl",
age: 38
}
]
const result = results.map((rec) => {
return {
name: rec.name,
surname: rec.surname
}
})
console.log(result)
Or delete fields that is useless
const results = [
{
name: "John",
surname: "Fool",
age: 22
},
{
name: "Erik",
surname: "Owl",
age: 38
}
]
const result = results.map((rec) => {
delete rec.age
return rec
})
console.log(result)
I suggest you can tell more about what you will need to perform on the output to get the answer that can help.
Case 1. if your original list will survive and you accept your "modified list" to always follow the original list, you may use a generator to wrap your original object, by always not returning those extra properties.
Case 2. if you really want a query system, you may try using real DB thing such as levelDB
Case 3. if you need to display the modified list, write a simple wrapper to fit the format of each list item
Case 4. if you need to snapshot the modified list as object, the method you already made is already a very reasonable method
Case 5. if you need to snapshot the modified list as another output, you can try to directly obtain such output rather than making the intermediate object
You can use map and reduce to simplify this, which obviates the need to create a new array.
var results = [ { name: "John", surname: "Fool", age: 22 }, { name: "Erik", surname: "Owl", age: 38 } ];
let keys = ['name', 'surname'];
var filtered = results.map(obj=>
keys.reduce((acc,curr)=>(acc[curr]=obj[curr],acc), {}));
console.log(filtered);
You can also use object destructuring.
var results = [ { name: "John", surname: "Fool", age: 22 }, { name: "Erik", surname: "Owl", age: 38 } ];
var filtered = results.map(({name,surname})=>({name,surname}));
console.log(filtered);
Take a look at Array.map.It creates the transformed array.
let arr = [
{
name: "John",
surname: "Fool",
age: 22
},
{
name: "Erik",
surname: "Owl",
age: 38
}
]
let result = arr.map((elem) => {
return {
name: elem.name,
surname: elem.surname
}
});
console.log(result);
You can use Array.map() to transform individual elements of the array. And in the callback function use Object destructuring assignment to use only the keys you are interested in and return a new object with only those keys.
let results = [
{ name: "John", surname: "Fool", age: 22 },
{ name: "Erik", surname: "Owl", age: 38 }
];
let modified = results.map(({name, surname}) => ({name, surname}));
console.log(modified);
I want to display the array but only with name and age
const users = [{name: 'john', age: 20, instrument: 'guitar'}, {name: 'mary', age: 20, instrument: 'piano'}];
let userList = users.map(users => {name: users.name, users.instrument })
console.log(userList);
didn't work. I'm missing a return somewhere right?
You should wrap the object statement in each iteration with ().
Also, I prefer using Destructuring assignment:
const users = [{name: 'john', age: 20, instrument: 'guitar'}, {name: 'mary', age: 20, instrument: 'piano'}];
var new_users = users.map(({name,instrument}) => ({name, instrument}));
console.log(new_users);
You just need to wrap object inside ()
const users = [{name: 'john', age: 20, instrument: 'guitar'}, {name: 'mary', age: 20, instrument: 'piano'}];
var result = users.map(user => ({ name: user.name, instrument: user.instrument }));
console.log(result)
You forgot an = when setting users.
Inside the map function, you called the run-through-object users but use user.
You forgot an ' after 'guitar
You didn't set the key for the instrument value in the mapping function
You need to add brackets () around the object in the mapping function as it will be treated as arrow function if forgotten
In the end it should look like this:
const users = [{name: 'john', age: 20, instrument: 'guitar'}, {name: 'mary', age: 20, instrument: 'piano'}];
const mapped = users.map(user => ({name: user.name, instrument: user.instrument}));
console.log(mapped);
I have an array with objects and want to convert this to an array containing the same values but with different key names. (JavaScript)
For example, an array of
[{name: "Bob", age: 50, person: true}, {name: "Jerry", age: 20, person: true}]
becomes
[{identification: "Bob", years: 50, person: true}, {identification: "Jerry", years: 20, person: true}]
Using the Map function works perfectly here.
const people = [
{name: "Bob", age: 50, person: true},
{name: "Jerry", age: 20, person: true}
];
const formatted = people.map((person) => ({
identification: person.name,
years: person.age,
person: person.person
});
This should work for this problem.
I think that you may use the map method this method returns and array with the same length as the one you are mapping:
const array = [{name: "Bob", age: 50, person: true}, {name: "Jerry", age: 20, person: true}];
let newKeysArray = array.map( a => {
let obj = {
identification: person.name,
years: person.age,
person: person.person
};
return obj
} );
So inside the map you are assigning the values that you need to a new object and return the object as the mapped item.
Just in case you prefer to modify the objects in place, you can make use of a strategy by nverba here:
let rows = [
{name: "Bob", age: 50, person: true},
{name: "Jerry", age: 20, person: true}
];
let keyMaps = [
['name', 'identification'],
['age', 'years'],
];
for(let keyMap of keyMaps)
for(let row of rows)
delete Object.assign(row, {[keyMap[1]]: row[keyMap[0]] })[keyMap[0]];
console.log(rows);
keyMap[1] is the new key. keyMap[0] is the old key. Object.assign takes the value of the old key and places it in the new key. The delete keyword is confusing, but it doesn't apply to row as a whole. It's only deleting the old key.
I have the following array.
var gillFamily = [
{ name: 'john', age: 20 },
{ name: 'richard', age: 27 },
{ name: 'debbie', age: 55 },
{ name: 'dan', age: 25 },
{ name: 'robin', age: 60 }
];
I need to print the names with the lastname "Gill" added to them using lodash.
I've tried this which was the closest I got:
_.map(gillFamily, "name") + " Gill";
but that only adds Gill to the last name in the array.
How do I add the name to all items in the array?
One option is:
_.map(gillFamily, (el) => el.name + " Gill");
In case that the environment doesn't support ES6:
_.map(gillFamily, function(el) {
return el.name + " Gill"
});
You could also use Array.prototype.map function.
You need to access the name property inside the Object and then add the Gill string to that name.
var gillFamily = [ {name: 'john', age: 20},
{name: 'richard', age: 27},
{name: 'debbie', age: 55},
{name: 'dan', age :25},
{name: 'robin', age : 60}];
var gillFamilyWithLastNameAdded = _.map(gillFamily, person => person.name + " Gill");
console.log(gillFamilyWithLastNameAdded);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
Using the map function you can map each element with the last name appended to using the following. Using _.each(), you can loop over the array of objects and update the property/properties desired. This probably may not be the best/most efficient technique but it's the best I could find by just reading the docs.
Note: This will overwrite the original object.
Disclaimer: I'm not an active lodash user.
// Setup example data
var gillFamily = [{
name: 'john',
age: 20
}, {
name: 'richard',
age: 27
}, {
name: 'debbie',
age: 55
}, {
name: 'dan',
age: 25
}, {
name: 'robin',
age: 60
}];
// Display the initial values
document.getElementById("start").innerText = JSON.stringify(gillFamily);
// Append family name on the current family member's name
var gillFamilyWithLastNames = _.each(gillFamily, function(el) {
// Append 'Gill' to the end of the existing name
el.name += ' Gill';
});
// Show the results
document.getElementById("end").innerText = JSON.stringify(gillFamilyWithLastNames);
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
<p>Starting Data</p>
<pre id="start"></pre>
<p>Ending Data</p>
<pre id="end"></pre>
Javascript Array push issue
I have a object:
people: [{name: peter, age: 27, email:'peter#abc.com'}]
I want to push:
people.push({
name: 'John',
age: 13,
email: 'john#abc.com'
});
people.push({
name: 'peter',
age: 36,
email: 'peter#abc.com'
});
The finally I want is:
people: [
{name: 'peter', age: 36, email:'peter#abc.com'},
{name: 'john', age: 13, email:'john#abc.com'},
]
I dont have any key but the email is a unique
You can also do like this by generating an Array method. It takes two arguments. First one designates the object to push and the second is the unique property to check to replace if a previously inserted item exists.
var people = [{name: 'peter', age: 27, email:'peter#abc.com'}];
Array.prototype.pushWithReplace = function(o,k){
var fi = this.findIndex(f => f[k] === o[k]);
fi != -1 ? this.splice(fi,1,o) : this.push(o);
return this;
};
people.pushWithReplace({name: 'John', age: 13, email: 'john#abc.com'}, "email");
people.pushWithReplace({name: 'peter', age: 36, email: 'peter#abc.com'},"email");
console.log(people);
There is no "update" method as is in JavaScript.
What you have to do, is simply looping through your array first to check if the object is already inside.
function AddOrUpdatePeople(people, person){
for(var i = 0; i< people.length; i++){
if (people[i].email == person.email){
people[i].name = person.name;
people[i].age = person.age;
return; //entry found, let's leave the function now
}
}
people.push(person); //entry not found, lets append the person at the end of the array.
}