How to get transform from object to specific key value pair using lodash? - arrays

Products: [
{_id: 'xx1', name: 'p1', sku: 's1'},
{_id: 'xx2', name: 'p2', sku: 's2'},
{_id: 'xx3', name: 'p3', sku: 's3'}
]
I want to replace word '_id' with 'product', and to map to below result:
productArray = [ {product: 'xx1'}, {product: 'xx2'}, {product: 'xx3'} ];
I tried lodash code something like below but it just doesn't seem to work correctly:
let productArray = _.map(Products, '_id');
Can anyone help me on this? Thank you

Why would you even need to use lodash? Map will easily do the job.
const products = [{
_id: 'xx1',
name: 'p1',
sku: 's1'
},
{
_id: 'xx2',
name: 'p2',
sku: 's2'
},
{
_id: 'xx3',
name: 'p3',
sku: 's3'
}
];
const outProducts = products.map(x => {
return {
product: x._id
}
});
console.log(outProducts);

Related

Grouping Data in TypeScript Array

I have JSON data that looks like this:
[
{
"id": 1,
"tags": [
"Test 1",
"Test 2",
"Test 3"
]
},
{
"id": 2,
"tags": [
"Test 2",
"Test 3",
"Test 4"
]
},
{
"id": 3,
"tags": [
"Test 3",
"Test 4"
]
}
]
I would like to transform this into data that looks like this:
[
{
"name": "Test 1",
"count": 1
},
{
"name": "Test 2",
"count": 2
},
{
"name": "Test 3",
"count": 3
},
{
"name": "Test 4",
"count": 1
}
]
I can think of some brute ways to do this, but I'm hoping there is something more performant and a little sexier? Possibly using .groupBy() or .reduce()?
Thanks for taking the time to check out my question.
I would:
parse the json
gather all tags in an array
count occurences using one of the approaches in Counting the occurrences / frequency of array elements
interface Item {
id: number,
tags: string[]
}
function countOccurences(a: string[]) {
return a.reduce(function (acc: {[key: string]: number}, curr: string) {
acc[curr] ??= 0;
acc[curr]++;
return acc;
}, {});
}
const data: Item[] = JSON.parse(json);
const tagOccurences = countOccurences(data.flatMap(o => o.tags))
Playground link
You can use reduce inside reduce to group the tags.
const array = [{
id: 1,
tags: ['Test 1', 'Test 2', 'Test 3'],
},
{
id: 2,
tags: ['Test 2', 'Test 3', 'Test 4'],
},
{
id: 3,
tags: ['Test 3', 'Test 4'],
},
];
const frequencies = Object.values(array.reduce((acc, curr) =>
curr.tags.reduce(
(nAcc, tag) => ((nAcc[tag] ??= {name: tag,count: 0}),nAcc[tag].count++,nAcc),
acc
), {}
));
console.log(frequencies);
In TypeScript:
const array = [{
id: 1,
tags: ['Test 1', 'Test 2', 'Test 3'],
},
{
id: 2,
tags: ['Test 2', 'Test 3', 'Test 4'],
},
{
id: 3,
tags: ['Test 3', 'Test 4'],
},
];
type Frequency = {
name: string,
count: number
}
const frequencies = Object.values(array.reduce((acc, curr) =>
curr.tags.reduce(
(nAcc, tag) => ((nAcc[tag] ??= {name: tag,count: 0}),nAcc[tag].count++,nAcc),
acc
), {} as Record<string, Frequency>
));
console.log(frequencies);
Playground
Using for...of iteration and a Map as a cache is a very straightforward approach... and sexy.
TS Playground
type TagsWithId = {
id: number;
tags: string[];
};
type TagCount = {
count: number;
name: string;
};
function verySexyTagCounter (input: TagsWithId[]): TagCount[] {
const map = new Map<string, number>();
for (const {tags} of input) {
for (const name of tags) {
map.set(name, (map.get(name) ?? 0) + 1);
}
}
return [...map.entries()].map(([name, count]) => ({name, count}));
}
const json = `[{"id":1,"tags":["Test 1","Test 2","Test 3"]},{"id":2,"tags":["Test 2","Test 3","Test 4"]},{"id":3,"tags":["Test 3","Test 4"]}]`;
const input: TagsWithId[] = JSON.parse(json);
const result = verySexyTagCounter(input);
console.log(result);

How to manipulate the object inside the array using javascript?

var arr = [
{ id: 1, name: 'Ahmed Malick', school: 'TEWGS' },
{ id: 2, name: 'Tehmeed Anwar', school: 'DGS' },
{ id: 3, name: 'Azhar Yameen', school: 'DGS' }
]
I want this output:
The student name is his id is and he studies in
Can you please show me what kind of output you expect. Then i will try to solve it.
I'm not sure if this is what you want
var arr = [
{ id: 1, name: "Ahmed Malick", school: "TEWGS" },
{ id: 2, name: "Tehmeed Anwar", school: "DGS" },
{ id: 3, name: "Azhar Yameen", school: "DGS" },
];
arr.map((student) => {
return `Name: ${student.name}, id: ${student.id}, he studies in: ${student.school}`;
}).forEach((output) => {
console.log(output);
});
If you want it in the DOM do this
let html = arr.map((student) => {
return `<p><strong>Name</strong>: ${student.name}, <strong>id</strong>: ${student.id},<strong> he studies in</strong> ${student.school}</p>`;
}).join("")
document.createElement("div").innerHTML = html
Try thatGood luck

How can i check additional category exist when mapping this array in react js?

Here, SubCategoryDetail contains Additional Category but SubCategoryDetail may not have an Additional Category. I need to check where the Additional Category exists then go to the AdditionalCategoryDetail option if not exist then show SubCategoryDetail products when I'm mapping this array.
categoryDetail: [
{
id: 0,
SubCategoryName: "Sewing Section",
SubCategoryDetail: [
{
id: 0,
AdditionalCategoryName: "Additional Category Name 0",
AdditionalCategoryDetail: [
{
id: 0,
ProductName: 'Product Name 0',
ProductImg: "images/AllCategories/SubCategories/3.png",
Price: '80.00',
Brand: 'Brand'
},
{
id: 1,
ProductName: 'Product Name 1',
ProductImg: "images/AllCategories/SubCategories/4.png",
Price: '70.00',
Brand: 'Brand'
}]
}]
},
{
id: 1,
SubCategoryName: "Cutting Section",
SubCategoryDetail: [
{
id: 0,
ProductName: 'Product Name 0',
ProductImg: "images/AllCategories/SubCategories/2.png",
Price: '100.00',
Brand: 'Brand'
},
{
id: 1,
ProductName: 'Product Name 1',
ProductImg: "images/AllCategories/SubCategories/2.png",
Price: '100.00',
Brand: 'Brand'
}
]
}
]
}
]
You can do something like this.
results = categoryDetail.map(categories => {
return categories.SubCategoryDetail.map(category => {
if (category.hasOwnProperty("AdditionalCategoryDetail")) {
return category.AdditionalCategoryDetail[0]
} else {
return category[0]
}
})[0]
})

Javascript arrays: How to remove the all matched elements which are contained in another array

I have 2 javascript arrays which are a, b and I want to remove the common elements from the array a.
Can you please help on this.
var a = [{
name: 'java',
id: '1'
},
{
name: 'php',
id: '2'
},
{
name: 'ruby',
id: '3'
},
{
name: 'phyton',
id: '4'
}
];
var b = [{
name: 'java',
id: '1'
},
{
name: 'php',
id: '2'
}
];
It's basically a simple filter operation. I'd take the ids from b into an array, then filter by those elements
var a = [{
name: 'java',
id: '1'
},
{
name: 'php',
id: '2'
},
{
name: 'ruby',
id: '3'
},
{
name: 'phyton',
id: '4'
}
];
var b = [{
name: 'java',
id: '1'
},
{
name: 'php',
id: '2'
}
];
const exists = b.map(e => e.id);
const res = a.filter(e => !exists.includes(e.id));
console.log(res);

How to filter all the fields in react?

How to filter all the fields in react?
I have written a code which only filters specified fields.
let filteredContacts=this.props.contacts.filter(
(contact)=>{
return contact.name.indexOf(this.state.search)!==-1;
}
);
the above code only returns filtered names...but i want to filter name,age,city work.
this is the data file:
export default function(){
return [{
key: 1,
name: 'Steve',
city: 'Paris',
}, {
key: 2,
name: 'Tim',
city: 'London',
}, {
key: 3,
name: 'Stella',
city: 'Bankok',
}, {
key: 4,
name: 'John',
city: 'Paris',
}];
}
i want to create a search bar which which filters all the fields suppose if i search john then the list of john should be displayed and if i search paris then all the entries which have paris should be displayed..So the code which i have written only searches for name as i have specified name..i want to search the inputed data to search all the fields.
The filter criteria can be the indexOf on Object.values() like below but it will only give a complete match
var data = [{
key: 1,
name: 'Steve',
city: 'Paris',
}, {
key: 2,
name: 'Tim',
city: 'London',
}, {
key: 3,
name: 'Stella',
city: 'Bankok',
}, {
key: 4,
name: 'John',
city: 'Paris',
}];
var value = 'Paris'
var newData = data.filter((obj) => {
return Object.values(obj).indexOf(value) > -1
})
console.log(newData)
Well, I fastly tried, do a loop on your keys. Maybe there's a more elegant way.
let filteredContacts=this.props.contacts.filter(
(contact)=>{
var found = false;
Object.keys(contact).map(function(key, index) {
if (contact[key].indexOf(this.state.search) >= 0)
found = true;
}
return found;
}
);

Resources