Create an array of objects? - javascript

arr = [
men: {name: "john", age:"30"},{name: "john2", age:"31"},
women: {name: "kim", age:"10"},{name: "karen", age:"33"}
]
I'm looking to create an array with properties men and women, and each of those will have a bunch of objects. How can I do that in JS?

First create object then array in it, so like this you can manage your data.
let arr = {
men: [
{name: 'john', age: 30},
{name: 'john2', age:33}
],
women: [
{name: 'kim', age: 30},
{name: 'kim2', age:33}
],
}
console.log( arr.men[0].name );
just extend the value in the men or women array.
Thanks!

You need an object in order to achieve this. After this, you will be able to manage the people object just anyhow you want.
var people = {
men: [
{name: "man1", age: 30},
{name: "man2", age: 31},
],
women: [
{name: "woman1", age: 30},
{name: "woman2", age: 31},
]
}
// Add to men
people.men.push({"man3", age: 32})
// Add to women
people.women.push({"woman3", age: 32});
// Print the people object
console.log(JSON.stringify(people, null, 2)); // pretty format

Related

lodash filter match if property value contains "x"

If I have an array of objects like so:
const array = [
{name: "Jim", attributes: "strong, handsome, tall", age: 28},
{name: "Alice", attributes: "blonde, thin, tall", age: 26},
{name: "Bob", attributes: "lazy, small, thin", age: 32}
]
Is there a way to use _.filter(array) to create a new array with objects whereby a property contains a value.
Something like _.filter(array, attributes.contains("tall")) would return desired result of:
[
{name: "Jim", attributes: "strong, handsome, tall", age: 28},
{name: "Alice", attributes: "blonde, thin, tall", age: 26}
]
This can be done with the built-in filter and checking if the attributes of the person includes "tall".
const array = [
{name: "Jim", attributes: "strong, handsome, tall", age: 28},
{name: "Alice", attributes: "blonde, thin, tall", age: 26},
{name: "Bob", attributes: "lazy, small, thin", age: 32}
];
const tallPeople = array.filter(
(person) => person.attributes.includes("tall")
);
console.log(tallPeople);
You can do this vanilla JS.
try the filter method, but please note it is a shallow copy - so if you update the original array, your filter will be different also.
array.filter(el => el.attributes.includes('tall'))
This is possible because the String type has the includes method.
Updated to use includes instead of contains. both work.

Using Array.map(), to extract values from array of key:value objects

I have been able to use the following code to extract values for a list of specific keys from an array of objects.
let keys = ['name', 'age'];
let employees = [
{name: 'Matt', employeeID: 123, performance: 'good', age: 21},
{name: 'Brian', employeeID: 321, performance: 'average', age: 32},
{name: 'David', employeeID: 456, performance: 'best', age: 35},
{name: 'Kevin', employeeID: 654, performance: 'poor', age: 38},
{name: 'Barrack', employeeID: 789, performance: 'super', age: 47},
];
let extracted = employees.map(object => keys.map(element => object[element]));
console.log(extracted); //result is [[Matt, 21.0], [Brian, 32.0], [David, 35.0], [Kevin, 38.0], [Barrack, 47.0]]
I have a hard time understanding conceptually how using two Array.map() methods nested within each other works like this. Can somebody walk me through how this actually works? For instance if I want to use only one Array.map() method to recreate the above, I end up with an array of truncated objects that still includes key:value pairs.
let truncated = employees.map(({name, age, ...rest}) => ({name, age}));
console.log(truncated); //result is [{age=21.0, name=Matt}, {age=32.0, name=Brian}, {age=35.0, name=David}, {name=Kevin, age=38.0}, {age=47.0, name=Barrack}]
On the first iteration of employees.map(), object is the object
{name: 'Matt', employeeID: 123, performance: 'good', age: 21}
We then execute keys.map().
On the first iteration, element is 'name', and we return object[element], which is 'Matt'. On the second iteration, element is 'age', and we return object[element], which is 21. map() combines these results into the array ['Matt', 21].
We then repeat the above for each object in the employees array, and make a list of all these results. This produces an array of arrays.
Array map takes an array of elements and transforms each element using the supplied function -
// input
[1,3,5,7].map(a => a + 10)
input
a => a + 10
output
1
1 + 10
11
3
3 + 10
13
5
5 + 10
15
7
7 + 10
17
// output
[11,13,15,17]
Now we look at it with a more simplified view -
// in // out
[ [
1, // => 11,
3, // => 13,
5, // => 15,
7, // => 17
] ]
And now expand it with a level of nesting using your objects -
[
{
name: 'Matt', // [ [
employeeID: 123, // "name", => "Matt",
performance: 'good', // "age" 21
age: 21 // ] ]
},
{
name: 'Brian', // [ [
employeeID: 321, // "name", => "Brian",
performance: 'average', // "age" 32
age: 32 // ] ]
},
{
name: 'David', // [ [
employeeID: 456, // "name", => "David",
performance: 'best', // "age" 35
age: 35 // ] ]
},
{
name: 'Kevin', // [ [
employeeID: 654, // "name", => "Kevin",
performance: 'poor', // "age" 38
age: 38 // ] ]
},
{
name: 'Barrack', // [ [
employeeID: 789, // "name", => "Barrack",
performance: 'super', // "age" 47
age: 47 // ] ]
}
]
[
[
"Matt",
21
],
[
"Brian",
32
],
[
"David",
35
],
[
"Kevin",
38
],
[
"Barrack",
47
]
]
[
["Matt",21],
["Brian",32],
["David",35],
["Kevin",38],
["Barrack",47]
]
You end up with a nested array because both maps return arrays. Your "inner" map returns an array of values based on the keys array, and that is returned to the "outer" map that's been iterating over the array of each object, which also returns an array.
// Create a new array by mapping over each object
employees.map(object => {
// For each key in the keys array return a
// new array of only those values of the
// properties of the object that match the key
return keys.map(element => object[element]);
});
let keys = ['name', 'age'];
let employees = [
{name: 'Matt', employeeID: 123, performance: 'good', age: 21},
{name: 'Brian', employeeID: 321, performance: 'average', age: 32},
{name: 'David', employeeID: 456, performance: 'best', age: 35},
{name: 'Kevin', employeeID: 654, performance: 'poor', age: 38},
{name: 'Barrack', employeeID: 789, performance: 'super', age: 47},
];
let extracted = employees.flatMap(object => keys.map(element => object[element]));
console.log(extracted);
What you are looking for should be a flatMap

Separate string into a set of objects

I have this string var string = "{name: Hello, age: 20}, {name: Nadia, age: 30}" returned from the backend. I created an object out of it by appending it to an empty array like so:
var array = [];
var array1 = array.push(string);
After appending to an array, I got the following result:
Array [
"{name: Hello, age: 20},
{name: Nadia, age: 30}
{name: Nadia, age: 30}
{name: Nadia, age: 30}
{name: Nadia, age: 30}"
]
My intended result is this:
Array [
"{name: Hello, age: 20}",
"{name: Nadia, age: 30}",
"{name: Nadia, age: 30}",
"{name: Nadia, age: 30}",
"{name: Nadia, age: 30}"
]
I have tried using split(",") but they're separated individually instead. How can I achieve the intended result? I'm very new to this.
UPDATE: The answer provided gave out not quite the result that I wanted. I have this larger set of objects. The solution returns me with 2 objects, with the second object being a combination of objects. Here's the output using the method in the answer:
Array [
"{name: Hello, age: 20}",
"{name: Nadia, age: 30}
{name: Nadia, age: 30}
{name: Nadia, age: 30}
{name: Nadia, age: 30}"
]
Also, I have asked my fellow backend dev to fix the json return, sadly they cannot change it. I'm not sure why. The only way I can handle this is on frontend.
Below method works but its a bit crude. But you can give it a try..
let str = "{name: Hello, age: 20}, {name: Nadia, age: 30}, {name: Nadia, age: 30}, {name: Nadia, age: 30}";
let x = str.replaceAll('}, ', '}/').split('/');
console.log(x);

What is smallest way to split object into array of object based on key/value pairs in Javascript?

I've got this object:
var obj = {
family : [{name: 'will', age: 30}, {name: 'husain', age: 12}],
friends : [{name: 'cody', age: 31}, {name: 'jeff', age: 11}],
school : [{name: 'daniel', age: 20}, {name: 'carl', age: 15}]
}
convert it into this
var obj = [
{family : [{name: 'will', age: 30}, {name: 'husain', age: 12}]},
{friends : [{name: 'cody', age: 31}, {name: 'jeff', age: 11}]},
{school : [{name: 'daniel', age: 20}, {name: 'carl', age: 15}]}
];
Write now I am using for..in to build a new array and create object with key as key for new object and so on.
I'm doing this right now
var arr = [];
for (let key in obj) {
arr.push({key: obj[key]})
}
I think Object.keys is your best option:
var obj = {
family : [{name: 'will', age: 30}, {name: 'husain', age: 12}],
friends : [{name: 'cody', age: 31}, {name: 'jeff', age: 11}],
school : [{name: 'daniel', age: 20}, {name: 'carl', age: 15}]
}
var r = Object.keys(obj).map(x => ({[x]: obj[x]}) )
console.log(r)

Omit array of keys with Underscore

Using Underscore (technically Lodash). Have an object that looks like the following.
var myObj = {
first: {name: 'John', occupation: 'Welder', age: 30},
second: {name: 'Tim', occupation: 'A/C Repair', kids: true},
third: {name: 'Dave', occupation: 'Electrician', age: 32},
fourth: {name: 'Matt', occupation: 'Plumber', age: 41, kids: false}
};
I also have a hash of arrays that I want to "clean" out of each object:
var excludes = {
first: ['name', 'age'],
second: ['occupation'],
fourth: ['kids]
};
The idea is that each of the elements in the array will be dropped from the object that has the matching key. Meaning my data will end up like this:
{
first: {occupation: 'Welder'},
second: {name: 'Tim', kids: true},
third: {name: 'Dave', occupation: 'Electrician', age: 32},
fourth: {name: 'Matt', occupation: 'Plumber', age: 41}
};
I was originally trying:
_.map(myObj, function(obj, k) {
if(_.has(excludes, k) {
// not sure what here
}
});
I was thinking of using omit at the innermost level, but I can only drop one key at a time, not a list of keys.
Actually, _.omit can take a list of keys:
result = _.transform(myObj, function(result, val, key) {
result[key] = _.omit(val, excludes[key]);
});

Categories