I have read several solutions to this problem here. When I try it, I continue to receive an error for the pop() method.
I have what is essentially a multidimensional array in javascript.
I am tasked with returning the array with the sensitive info removed (e.g. remove the SSN, in this example)
I thought I could use a foreach loop, and the pop() function to remove the last element of the child arrays, the SSN.
testing it using node on the commandline, the stdout is telling me that element.pop() is not a function. i've tried it with pop(), slice(), filter(), all with no success.
when running $> node filename.js
H:\Apache2\htdocs\test\filename.js:50
noppi[i] = element.pop();
^
TypeError: element.pop is not a function
let recs = [
{
ID: 1,
NAME: 'John',
EMAIL: 'john#example.com',
SSN: '123'
}, {
ID: 2,
NAME: 'Sally',
EMAIL: 'sally#example.com',
SSN: '456'
}, {
ID: 3,
NAME: 'Angie',
EMAIL: 'angie#example.com',
SSN: '789'
}
];
let i = 0;
let noppi = [];
recs.forEach(element => {
noppi[i] = element.pop();
i++;
});
console.log(noppi);
At the risk of sounding redundant, I'll briefly reiterate what the earlier answers have already stated.
The input data structure isn't a multi-dimensional array [ [ ... ], [ ... ] ] , it's an array of objects [ {...}, {...} ]. So you can't use Array methods like .pop() on the objects {...}.
Here's a simple one-liner that uses .forEach() and delete.
recs.forEach(obj => delete obj.SSN)
delete is an operator with one purpose: to remove an object's property like for example SSN: '123-45-6789'. Simple and perfect.
Note, .forEach() mutates the array, meaning that it's the original data being changed (see Minja's comment).
let recs = [
{
ID: 1,
NAME: 'John',
EMAIL: 'john#example.com',
SSN: '123'
}, {
ID: 2,
NAME: 'Sally',
EMAIL: 'sally#example.com',
SSN: '456'
}, {
ID: 3,
NAME: 'Angie',
EMAIL: 'angie#example.com',
SSN: '789'
}
];
recs.forEach(obj => delete obj.SSN);
console.log(recs)
Try this:
recs.forEach(element => {
noppi.push = element;
});
You are trying to use pop() on an object not an array
As per your need you need to remove SSN from your object, try below code it should work for you.
recs.forEach(element => {
const { SSN, ...rest } = element;
noppi.push(rest);
});
Here we are removing SSN from object and rest will push in noppi.
Related
I have a js file that is just a an array with the name and type of person. I am trying to write a function in my other file to iterate through that array of objects and return just the object that matches a certain criteria. Here is my code.
person.js
export const persons_options = [
{
name: 'Andrew',
type: 'Athlete',
},
{
name: 'Paul',
type: 'Worker',
},
{
name: 'Phil',
type: 'Developer',
},
]
utils.js
// params initialized already
person_type = params.subType
const name = persons_options.map((option) => {
if(person_type === option.type){
return option.name
}
})
const person = name
The issue is I know map creates a new array so the output is ,,Phil. How would I just return one of the object names instead of all of them.
find() will do the work
let persons_options = [
{
name: 'Andrew',
type: 'Athlete',
},
{
name: 'Paul',
type: 'Worker',
},
{
name: 'Phil',
type: 'Developer',
},
]
let obj = persons_options.find(o => o.type === 'Developer');
//to return name
console.log("name",obj.name);
console.log(obj);
You need to use the find function.
See here the list of functions that you can call on an array:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#instance_methods
filter might best suit your case if multiple results may be returned.
just wondering if someone could point me in the right direction of .map functionality. This is unfortunately something I'm struggling to get my head around.
If I had an object, lets say the following:
const myPetsAndFood = {
pets:[
{
species: "dog",
breed: "Labrador",
age: 12
},
{
species: "cat",
breed: "unknown",
age: 7,
},
{
species: "fish",
breed: "goldfish",
age: 1,
}
],
food: [
{
dogfood: 15.00,
},
{
catfood: 11.00,
},
{
fishfood: 4.00,
}
],
};
Could anyone explain how I'd utilise .map to obtain the data values of age and price if possible please?
A brief explanation or example is more than suffice, I'd appreciate any time/input possible. In all probability, I'll be sat here reading and trying to figure it out in the mean time.
If you got this far - Thank you for your time.
So the .map can only be used with arrays. This way you can not do something similar to:
myPetsAndFood.map()
Let's say you want do console.log the age. You would have to get the array first. So:
myPetsAndFood.pets.map((pet) => {
console.log(pet.age)
})
And it would print 12, followed by 7 followed by 1. If you want to store it inside an array you can create an array and use .push("//infos wanted to be pushed//")
Object.keys(myPetsAndFood).map(function(key, index) {
console.log(myPetsAndFood[key][0].dogfood);
console.log(myPetsAndFood[key][0].age);
});
You are going to have to figure out a way to replace the 0 with some sort of counter that will increment.
map is a method of arrays, it doesn't exist on objects. You could use it on the arrays within the object ( myPetsAndFood.pets.map( /* ... */ ) ) but you'd have to use a for loop or some other technique to parse each item in the object.
An example of how to use the map function for one of your arrays:
const agesArray = myPetsAndFood.pets.map((item) => {
return item.age;
});
So you have imbricated arrays here. This makes it so you have to go into your wanted array first before being able to execute your map.
For example: myPetsAndFood.pets.map(function)
The way that .map works is it executes your function on every element in your array and returns an array with the equivalency(source).
Therefore, in order to get the age of every pet, you have to tell your function to get your age property of your objects.
For example: myPetsAndFood.pets.map((pet) => pet.age)
This will return an array containing only the age of every one of your pets.
Now the problem with this is your second array. We cannot call the .map function on that array because your different properties don't have the same name. Therefore, your .map won't have any common ground to return a sensible array.
We can fix this issue by splitting your one variable into two: name and price for example. After this change, we can now call the .map on your array properly by telling it which property you need.
For example: myPetsAndFood.foods.map((food) => food.price)
Below is a full code snippet which should show off the above description.
const myPetsAndFood = {
pets:[
{
species: "dog",
breed: "Labrador",
age: 12
},
{
species: "cat",
breed: "unknown",
age: 7,
},
{
species: "fish",
breed: "goldfish",
age: 1,
}
],
foods: [
{
name: "dog",
price: 15.00,
},
{
name: "cat",
price: 11.00,
},
{
name: "fish",
price: 4.00,
}
],
};
const catAge = myPetsAndFood.pets.map((pet) => pet.age)
const foodPrice = myPetsAndFood.foods.map((food) => food.price)
console.log(catAge)
console.log(foodPrice)
This question already has answers here:
How to filter object array based on attributes?
(21 answers)
Closed last year.
Below is the array with objects:
myArray:[
{"name":"Ram", "email":"ram#gmail.com", "userId":"HB000006"},
{"name":"Shyam", "email":"shyam23#gmail.com", "userId":"US000026"},
{"name":"John", "email":"john#gmail.com", "userId":"HB000011"},
{"name":"Bob", "email":"bob32#gmail.com", "userId":"US000106"}
]}
I tried this but I am not getting output:
item= myArray.filter(element => element.includes("US"));
I am new to Angular.
let filteredArray = myArray.filter(function (item){
return item.userId.substring(0,2).includes('US')
})
Console.log(filteredArray)
//Output
[ { name: 'Shyam', email: 'shyam23#gmail.com', userId: 'US000026' },
{ name: 'Bob', email: 'bob32#gmail.com', userId: 'US000106' } ]
As noted by #halfer - You need to filter on the property that you are interested in - in this case - 'userId' - you can do this by simply adding the property into the code you already had tried and it will log out the specified items - or alternatively - you can make a utility function that takes the array, property and target string as arguments and this will allo2w you to search / filter other arrays and by any property and target string .
These two options are shown below and both log out the same results.
const myArray = [
{"name":"Ram", "email":"ram#gmail.com", "userId":"HB000006"},
{"name":"Shyam", "email":"shyam23#gmail.com", "userId":"US000026"},
{"name":"John", "email":"john#gmail.com", "userId":"HB000011"},
{"name":"Bob", "email":"bob32#gmail.com", "userId":"US000106"}
]
// option 1 - direct filtering
const matchingItems = myArray.filter(element => element.userId.includes("US"));
console.log(matchingItems);
// gives - [ { name: 'Shyam', email: 'shyam23#gmail.com', userId: 'US000026' }, { name: 'Bob', email: 'bob32#gmail.com', userId: 'US000106' } ]
//option 2 - create a function that takes arguments and returns the matches
const matches = (arr, prop, str) => {
return arr.filter(element => element[prop].includes(str));
}
console.log(matches(myArray, 'userId', 'US'));
// gives - [ { name: 'Shyam', email: 'shyam23#gmail.com', userId: 'US000026' }, { name: 'Bob', email: 'bob32#gmail.com', userId: 'US000106' } ]
var object = [{id:1, users:[{name:'john', name:'smith', name:'frank'}, {id:2, users:[{name:'lary'}, {name:'steve'}, {name:'joe'}]}]}]
output:
allUsers = [{name:'john'}, {name:'smith'}, {name:'frank'}, {name:’lary'}]
need answer in javascript. and also using lodash
I have not used lodash, but from the documentation I found a "flatten" -method, take a look here:
https://lodash.com/docs/4.17.5#flatten
Flattens array a single level deep.
I hope that helps you.
Edit: Ok here is the code example (Your curly braces were little off so I fixed them in this example. I hope this is what you were looking for.
But basically with map, get the users array from the individual object, then flatten the results after that.
var object = [
{
id:1,
users: [{name:'john'}, {name:'smith'}, {name:'frank'}]
},
{
id:2,
users: [{name:'lary'}, {name:'steve'}, {name:'joe'}]
}
];
const flattenUsers = lodash.flatten(object.map(id => id.users));
console.log(flattenUsers);
/*
Output:
[ { name: 'john' },
{ name: 'smith' },
{ name: 'frank' },
{ name: 'lary' },
{ name: 'steve' },
{ name: 'joe' } ]
*/
Can someone help me generate a new array of objects from an existing one using lodash? I've been trying a combination of _.zipObject and map but to no avail... basically, I have an array of objects like:
const names = [
{
first_name: 'nedd',
given_name: 'cersei'
},
{
first_name: 'tyrion',
given_name: 'tywin'
}
]
However, I want it to look like:
[
{
name: 'nedd'
},
{
name: 'cersei'
},
{
name: 'tyrion'
},
{
name: 'tywin'
},
]
I have tried various iterations of:
const newArray = _.zipObject( names, _.fill( Array(names.length), {name: ['first_name' || 'given_name']} ) );
But without any luck... can someone help?
Thanks in advance!
This might work:
_.flatMap(names, (n)=> [{name: n.first_name}, {name: n.given_name}]);
Use _.flatMap combined with _.map:
_.flatMap(names, (nameObj) => _.map(nameObj, (objVal) => { return { name: objVal }; }));