const data =
[{notification_id: 124, user_id: 10, story_id: 25, string: "liked on your story" }
{notification_id: 125, user_id: 12, story_id: 25, string: "liked on your story" }
{notification_id: 126, user_id: 15, story_id: 25, string: "liked on your story" }]
output: user 10,12 and 15 liked on your story ID 25
I want to show output like above. How to merge and show those like the output. Any idea?
You need to create a hash map, check the code snippet below:
const allData = [
{ name: 'John', story: 1 },
{ name: 'Ross', story: 2 },
{ name: 'Taylor', story: 1 },
{ name: 'Jimmy', story: 2 },
{ name: 'Amanda', story: 3 },
];
const hash = {};
for (let data of allData) {
if (data.story in hash) hash[data.story] = [...hash[data.story], { ...data }];
else hash[data.story] = [{ ...data }];
}
console.log(hash);
You should use Map, which is what I would suggest. The code below does the same thing but using Maps.
const allData = [
{ name: 'John', story: 1 },
{ name: 'Ross', story: 2 },
{ name: 'Taylor', story: 1 },
{ name: 'Jimmy', story: 2 },
{ name: 'Amanda', story: 3 },
];
const hash = new Map();
for(let data of allData) {
const currentVal = hash.get(data.story);
if (currentVal) hash.set(data.story, [...currentVal, {...data}])
else hash.set(data.story, [{...data}])
}
console.log(hash);
I cann't comment. So i write here!
Are you wanting ...
result = [
{
story_id : 25,
user_id : [10, 12, 15]
}
]
Right?
This is solution of me
const data =
[{notification_id: 124, user_id: 10, story_id: 25, string: "liked on your story" }
{notification_id: 125, user_id: 12, story_id: 25, string: "liked on your story" }
{notification_id: 126, user_id: 15, story_id: 25, string: "liked on your story" }]
var result = data.reduce((res, item) => {
let storyID = item.story_id;
if (typeof res[storyID] == 'undefined') {
res[storyID] = {
story_id: storyID,
user_id: []
}
}
res[storyID].user_id.push(item.user_id);
return res;
}, []);
result = Object.values(result);
Related
I want to copy value of name and age into another array, below code is working fine, But I wanted to know better way to do it.
const users = [
{ id: 0, name: 'John', age:34 },
{ id: 1, name: 'Wayne', age:44 },
{ id: 2, name: 'David', age:24 },
];
let values=[];
users && users.map(user => {
values.push(user['name'])
values.push(user['age'])
})
console.log(values);
output
['John', 34, 'Wayne', 44, 'David', 24]
You can bind each items to an array containing both its name and age and then flattern these arrays.
This can be done using Array#FlatMap
const users = [
{ id: 0, name: 'John', age:34 },
{ id: 1, name: 'Wayne', age:44 },
{ id: 2, name: 'David', age:24 },
];
const nameAndAges = users.flatMap(user => [user.name, user.age])
console.log(nameAndAges)
Your solution looks good, this can be also solved in different ways, I guess you may want to create function for handling this.
const users = [
{ id: 0, name: 'John', age: 34 },
{ id: 1, name: 'Wayne', age: 44 },
{ id: 2, name: 'David', age: 24 },
];
const result = mapArrayToProps(users, ['name', 'age']);
function mapArrayToProps(arr, props) {
return arr.flatMap(obj => mapObjectToProps(obj, props));
}
function mapObjectToProps(obj, props) {
return props.map(prop => obj[prop])
}
console.log(result);
I see that all the loops for objects returns the key as string and the value, but I want to operate on the keys of the object itself. If I have this object:
const data = {
person1: [
{ id: 1, name: Mike, age: 24 },
{ id: 2, name: Bob, age: 31 }
],
person2: [
{ id: 3, name: Christin, age: 21 },
{ id: 4, name: Michelle, age: 33 }
],
}
const removePersonById = (id) => {
// Check which person the id belongs to and remove that person
const persons = Object.keys(data).map(person => ...)
}
I wanted to loop through data and run .includes on each person in order to remove them by the id, but I am at a loss on how to do that.
You can loop through all keys and delete that the person you want by id using the filter() method
const removePersonById = (id) => {
var all = Object.keys(data);
for(let person of all){
data[person] = data[person].filter(a => a.id!=id);
}
}
You could get the values and find the index. Then splice.
const
removePersonById = id => {
Object.values(data).forEach(a => {
const index = a.findIndex(o => o.id === id);
if (index !== 0) a.splice(index, 1);
});
};
You could use .some()
const data = {
person1: [
{ id: 1, name: "Mike", age: 24 },
{ id: 2, name: "Bob", age: 31 }
],
person2: [
{ id: 3, name: "Christin", age: 21 },
{ id: 4, name: "Michelle", age: 33 }
],
}
const removePersonById = (id) => {
// Check which person the id belongs to and remove that person
Object.keys(data).map(person => {
if (data[person].some(p => p.id === id)) delete data[person];
})
}
removePersonById(3)
console.log(data)
Use Object.entries() so you can iterate over the keys and values together. Then you can test the value to see if the id is found.
Then use the delete operator to remove that key from the object.
const removePersonById = id => {
delete data[id];
};
const data = {
person1: [
{ id: 1, name: "Mike", age: 24 },
{ id: 2, name: "Bob", age: 31 }
],
person2: [
{ id: 3, name: "Christin", age: 21 },
{ id: 4, name: "Michelle", age: 33 }
],
};
const removePersonById = (id) =>
Object.entries(data).forEach(([key, value]) => {
if (value.some(({id: personid}) => personid == id)) {
delete data[key];
}
});
removePersonById(3);
console.log(data);
let data = {
person1: [
{ id: 1, name: "Mike", age: 24 },
{ id: 2, name: "Bob", age: 31 }
],
person2: [
{ id: 3, name: "Christin", age: 21 },
{ id: 4, name: "Michelle", age: 33 }
],
}
const removePersonById = (id) => {
// Check which person the id belongs to and remove that person
data = Object.keys(data).reduce((acc,key) => {
if(data[key].some(person=>person.id===id)) return acc
acc[key]= data[key]
return acc
}, {})
console.log(`Remove person with ID ${id}: `,data)
}
removePersonById(1)
i have this array of obj
const pressure = [
{
date: "2021-11-03T23:51:55.875Z",
diastolica: 72,
pulsazione: 69,
sistolica: 130,
user: "61830313ba36bf2504df0ec3",
__v: 0,
_id: "6183209bf91a7ed54a76c05e",
},
{
date: "2021-11-03T23:52:09.684Z",
diastolica: 75,
pulsazione: 71,
sistolica: 135,
user: "61830313ba36bf2504df0ec3",
__v: 0,
_id: "618320a9f91a7ed54a76c061",
},
];
What I would like to get is an array of objects formatted like this
[
{
name: "Sistolica",
data: [130,135],
},
{
name: "Diastolica",
data: [72,75]
},
{
name: "Pulsazione",
data: [69,71],
},
],
For use within apex charts
The solution I found is not suitable and above all it is not reusable, if I passed an array that does not have the same keys that I indicated in my helper function, everything would be for the worse.
Can anyone help me with this?
I post the solution I had adopted, but I know it's really awful
export const setupGraphSeries = (data) => {
const sistolica = [];
const diastolica = [];
const pulsazione = [];
const formatter = data.map((item) => {
sistolica.push(item["sistolica"]);
diastolica.push(item["diastolica"]);
pulsazione.push(item["pulsazione"]);
return [
{ name: "Sistolica", data: sistolica },
{ name: "Diastolica", data: diastolica },
{ name: "Pulsazione", data: pulsazione },
];
});
return formatter;
};
One way is to just map over an array of the required properties. This does mean mapping over pressures once per item:
const pressure = [
{
date: "2021-11-03T23:51:55.875Z",
diastolica: 72,
pulsazione: 69,
sistolica: 130,
user: "61830313ba36bf2504df0ec3",
__v: 0,
_id: "6183209bf91a7ed54a76c05e",
},
{
date: "2021-11-03T23:52:09.684Z",
diastolica: 75,
pulsazione: 71,
sistolica: 135,
user: "61830313ba36bf2504df0ec3",
__v: 0,
_id: "618320a9f91a7ed54a76c061",
},
];
const params = ["diastolica","pulsazione","sistolica"];
const result = params.map( name => ({
name,
data: pressure.map(x => x[name])
}));
console.log(result);
Another way is to reduce the original keeping track of whether you have that item yet. This doesnt require multiple passes over the original data but is a little more complex:
const pressure = [
{
date: "2021-11-03T23:51:55.875Z",
diastolica: 72,
pulsazione: 69,
sistolica: 130,
user: "61830313ba36bf2504df0ec3",
__v: 0,
_id: "6183209bf91a7ed54a76c05e",
},
{
date: "2021-11-03T23:52:09.684Z",
diastolica: 75,
pulsazione: 71,
sistolica: 135,
user: "61830313ba36bf2504df0ec3",
__v: 0,
_id: "618320a9f91a7ed54a76c061",
},
];
const params = ["diastolica","pulsazione","sistolica"];
const result = Object.values(pressure.reduce( (a,item) => {
for(var i=0;i<params.length;i++){
const name = params[i];
a[name] = a[name] || {name,data:[]}
a[name].data.push(item[name]);
}
return a;
},{}));
console.log(result);
I have this initial array:
const initialData = [
{
day: 1,
values: [
{
name: 'Roger',
score: 90,
},
{
name: 'Kevin',
score: 88,
},
{
name: 'Steve',
score: 80,
},
],
},
{
day: 2,
values: [
{
name: 'Roger',
score: 70,
},
{
name: 'Michael',
score: 88,
},
],
},
{
day: 3,
values: [
{
name: 'Steve',
score: 97,
},
],
},
];
to be converted into:
const result = [
{
name: 'Roger',
scores: [90, 70, null],
},
{
name: 'Kevin',
scores: [88, null, null],
},
{
name: 'Steve',
scores: [80, null, 97],
},
{
name: 'Michael',
scores: [null, 88, null],
},
];
I'm trying to use array map and create temporary array:
const holder = [];
initialData.map()
but to no avail
You can do this in a couple of steps - first reduce so you can index by name, and then map those entries to the format you expected
const initialData = [{day:1,values:[{name:"Roger",score:90},{name:"Kevin",score:88},{name:"Steve",score:80}]},{day:2,values:[{name:"Roger",score:70},{name:"Michael",score:88}]},{day:3,values:[{name:"Steve",score:97}]}];
var result = Object.entries(initialData.reduce( (acc,item) => {
item.values.forEach( v => {
if(!acc[v.name]) acc[v.name] = {};
acc[v.name][item.day] = v.score;
});
return acc;
},{})).map( ([name,days]) => ({
name,
scores: new Array(initialData.length).fill(null).map( (_,i) => days[i+1] || null)
}))
console.log(result);
You could use reduce and forEach to create one object for each name and then to get an array from that object you can just use Object.values method.
const data = [{"day":1,"values":[{"name":"Roger","score":90},{"name":"Kevin","score":88},{"name":"Steve","score":80}]},{"day":2,"values":[{"name":"Roger","score":70},{"name":"Michael","score":88}]},{"day":3,"values":[{"name":"Steve","score":97}]}]
const obj = data.reduce((r, { values }, i) => {
values.forEach(({ name, score }) => {
if (!r[name]) r[name] = { name, scores: Array(data.length).fill(null)}
r[name].scores[i] = score
})
return r;
}, {})
const result = Object.values(obj)
console.log(result)
activePath would change dynamically based on api call , how to pull object based on the activePath string that matches in nested object ?
path examples : Drug/GetRefills in this case it should push data.Drug.getRefills and if path is Payment/getAccount it should push data.Payment.getAccount
main.js
const data =
[{
id: 11,
name: "Drug",
children: [{
id: 12,
name: "getRefills"
}, {
id: 13,
name: "getDetails"
}]
}, {
id: 14,
name: "Payment",
children: [{
id: 15,
name: "getAccount"
}, {
id: 16,
name: "getAccountDetails"
}]
}]
function getModelData(data){
var activePath = "Drug/GetRefills";
var _interfaces = [];
$.each(data, function(id, item){
if (activePath.toLowerCase().includes(item.name)) {
console.log('OBJ', item);
_interfaces.push(item); // it should push getrefills object into interfaces
}
});
return _interfaces;
}
You can use recursion to find the object (similar to DFS):
const data = [{
id: 11,
name: "Drug",
children: [{
id: 12,
name: "getRefills"
}, {
id: 13,
name: "getDetails"
}]
}, {
id: 14,
name: "Payment",
children: [{
id: 15,
name: "getAccount"
}, {
id: 16,
name: "getAccountDetails"
}]
}];
function getModelData(path) {
function find(arr, [key, ...rest]) {
const obj = arr.find(o => o.name === key);
if (!obj) return null;
return rest.length ? find(obj.children || [], rest) : obj;
}
return find(data, path.split('/'));
// Instead of returning, add the found object to _interfaces
}
console.log(getModelData('Drug/getRefills'));
console.log(getModelData('Drug/getRefillsss'));
console.log(getModelData('Payment/getAccountDetails'));
I think you are looking for some util like flat. Here is the very basic example.
const data = [
{
id: 11,
name: "Drug",
children: [
{
id: 12,
name: "getRefills"
},
{
id: 13,
name: "getDetails"
}
]
},
{
id: 14,
name: "Payment",
children: [
{
id: 15,
name: "getAccount"
},
{
id: 16,
name: "getAccountDetails"
}
]
}
];
function flat(array) {
return array.reduce((m, {name, children}) => {
children.forEach((child) => {
const {name:cname} = child
const fullName = `${name.toLowerCase()}/${cname.toLowerCase()}`
if(!m[fullName]) m[fullName] =[]
m[fullName].push(child)
})
return m
},{})
}
function getModelData(path, data) {
return flat(data)[path.toLowerCase()];
}
var activePath = "Drug/GetRefills";
console.log(getModelData(activePath, data));
//Output
[ { id: 12, name: 'getRefills' } ]
Here is an example how you can get the right object from the data with the filter function from lodash.
const activePath = "Drug/getRefills";
// get name
let name = activePath.substr(0, activePath.indexOf('/'));
// get detail
let detail = activePath.substr(activePath.indexOf('/') + 1);
const data =
[{
id: 11,
name: "Drug",
children: [{
id: 12,
name: "getRefills"
}, {
id: 13,
name: "getDetails"
}]
}, {
id: 14,
name: "Payment",
children: [{
id: 15,
name: "getAccount"
}, {
id: 16,
name: "getAccountDetails"
}]
}]
// Get data with lodash filter
const currentName = _.filter(data, d => d.name === name);
const currentDetail = _.filter(currentName[0].children, c => c.name === detail);
console.log(currentDetail[0]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
const data = [{
id: 11,
name: "Drug",
children: [{
id: 12,
name: "getRefills"
}, {
id: 13,
name: "getDetails"
}]
}, {
id: 14,
name: "Payment",
children: [{
id: 15,
name: "getAccount"
}, {
id: 16,
name: "getAccountDetails"
}]
}];
function getModelData(data,activePath){
var activePaths = activePath.split("/"),
_interfaces = [];
$.each(data, function(index, item){
if(!item.children || item.children.length == 0){
return false; //break
}
if(activePaths[0].toLowerCase() != item.name.toLowerCase()){
return true;//continue
}
childs = item.children;
$.each(childs,function(name,item){
item.name.toLowerCase() === activePaths[1].toLowerCase() && _interfaces.push(item);
});
});
return _interfaces;
}
console.log(getModelData(data,'Drug/getRefills'));
console.log(getModelData(data,'Payment/getAccountDetails'));