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' } ]
*/
Related
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.
I have an array of objects, for example
arr = [
{
date: "2020-03-20T11:40:07.620Z",
name: "whatever",
id: "abc123"
},
{
date: "2020-03-21T11:21:07.620Z",
name: "whatever1",
id: "def455"
},
{
date: "2020-03-22T11:54:07.620Z",
name: "whatever2",
id: "abc123"
}
]
Actual data is more than this. I've simplified the array.
Here, id is the key which can be same in more than 1 array of objects, for example in 1st and 3rd id is same.
I want to check if more than 1 objects contain the same value (id). If yes, add another array (sameIdArray) in the first object where id is same (1st in this case) and this array will now contain all those objects where that same value (id) was found and remove them from the actual array. The final array structure will be something like this.
arr = [
{
date: "2020-03-20T11:40:07.620Z",
name: "whatever",
id: "abc123",
sameIdArray: [
{
date: "2020-03-22T11:54:07.620Z",
name: "whatever2",
id: "abc123"
}
]
},
{
date: "2020-03-21T11:21:07.620Z",
name: "whatever1",
id: "def455"
}
]
You can use the groupBy functionality. You can group your data by id and use it accordingly.
You can use libraries like underscore or lodash, if using JavaScript
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 }; }));
I have a fairly complex array generated from Google's natural language API. I feed it a paragraph of text and out comes lots of language information regarding such paragraph.
My end goal is to find "key words" from this paragraph, so, to achieve this I want to put all the "entities" into a flat array, count the duplicates, and then consider words with the highest amount of duplicates to be "key words". If it doesn't find any then I'll cherry pick words from entities I consider most significant.
I already know the entities that could exist:
var entities = [
'art',
'events',
'goods',
'organizations',
'other',
'people',
'places',
'unknown'
];
Here is an example structure of the array I'm working with.
input = [
{
language: {
entities: {
people: [
{
name: "Paul",
type: "Person",
},
{
name: "Paul",
type: "Person",
},
],
goods: [
{
name: "car",
type: "Consumer_good",
}
], //etc
}
}
}
];
output = ["Paul", "Paul", "car"...];
My question is - what is the best way to convert my initial array into a flat array to then find the duplicates without using a whole bunch of FOR loops?
There is no way around loops or array functions if you work with dynamic input data.
You can access all the values using this format:
input[0]["language"]["entities"]["people"][0].name
input = [
{
language: {
entities: {
people: [
{
name: "Paul",
type: "Person",
},
{
name: "Paul",
type: "Person",
},
],
goods: [
{
name: "car",
type: "Consumer_good",
}
], //etc
}
}
}
];
console.log(input[0]["language"]["entities"]["people"][0].name);
Then you could do something like this:
for (var entry in input[0]["language"]["entities"]) {
console.log(entry);
}
OR, if I understood you wrong,
You can use this to turn the javascript Object into an array using this (requires jquery):
var myObj = {
1: [1, 2, 3],
2: [4, 5, 6]
};
var array = $.map(myObj, function(value, index) {
return [value];
});
console.log(array[0][0]);
console.log(array[0]);
console.log(array);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This will output
1
[1, 2, 3]
[[1,2,3],[4,5,6]]
You could iterate through input.language.entities in a recursive way and collect all the .name properties into an array. Then you have only one for loop :-).
After doing that, you can iterate through it to find the duplicates. If you sort it alphabetical before it is easier (if two or more consecutive entries are equal, there are duplicates).
But it could be a bit dangerous if google changes the api or if it delivers crap data because of a malfunction.
Isn't input.language.entities already flat enough to work with it?
I ended up doing something like this. It's not pretty but it gets the job done.
var result = [];
var known_entities = ['art','events','goods','organizations','other','people','places','unknown'];
for(i=0; i < known_entities.length; i++){
var entity = known_entities[i];
if(language.entities[entity]){
for(var j in language.entities[entity]){
var word = language.entities[entity][j].name
result.key_words.push(word);
}
}
}
I have this array:
var myArray = [
{ familyName: 'one', subfamilies:
[ { subfamilyName: 'subOne', subItems:
[ { name: 'subOne', code: '1' },
{ name: 'subTwo', code: '2' }
] }
]
},
{ familyName: 'two', subfamilies:
[ { subfamilyName: 'subTwo', subItems:
[ { name: 'subOne', code: '1' },
{ name: 'subTwo', code: '2' },
{ name: 'subTwo', code: '3' }
] }
]
}
]
I need to divide that array in two diferent arrays with the same length if possible (my real array is so much longer), but I am having some problems getting it done. I create 2 blank array and, with for sentence read all the items. First I push the subItems in one blank array, but cannot get the way to create a new subFamily in a blank array variable and then push the sutItems array.
How can be this done?
Thanks a lot in advance.
var myOtherArray = myArray.splice(myArray.length / 2 | 0);