rename all key's objects JS - javascript

I want to rename some of my key's object but with a map it sounds quite difficult (I'm a newbie) here is my array :
"platforms": [
{
"id": 6,
"name": "PC (Microsoft Windows)"
},
{
"id": 11,
"name": "Xbox"
},
{
"id": 14,
"name": "Mac"
},
{
"id": 48,
"name": "PlayStation 4"
},
{
"id": 130,
"name": "Nintendo Switch"
}
],
And this is what i want it to be :
"platforms": [
{
"id": 6,
"name": "PC"
},
{
"id": 11,
"name": "Xbox"
},
{
"id": 14,
"name": "Mac"
},
{
"id": 48,
"name": "PS4"
},
{
"id": 130,
"name": "Switch"
}
],
And here is my code :
const renderedResults = results.map((result, index) => {
const platformSliced = result.platforms.slice(0,3);
return (
{platformSliced.map((platform) =>
<span className="main-game-card-platform">
{platform.name}.replace('PC (Windows Microsoft)', 'PC')
</span>
)}
);
});
It doesn't work maybe I should do a condition, but how can I write it ? Thank you

Create an object where the keys are the strings you want changed, and the values the strings that should replace the old string.
With .map() method, return a new object for each item, where the id is unchanged. The name property should look first in the new "rewrites" object if the value of name exists as a key in the object. If it does, then the value should be used, otherwise there is no rewrite and the old name should be used.
const rewrites = {
"PC (Microsoft Windows)": 'PC',
"PlayStation 4": 'PS4',
"Nintendo Switch": 'Switch'
};
const platforms = [
{
"id": 6,
"name": "PC (Microsoft Windows)"
},
{
"id": 11,
"name": "Xbox"
},
{
"id": 14,
"name": "Mac"
},
{
"id": 48,
"name": "PlayStation 4"
},
{
"id": 130,
"name": "Nintendo Switch"
}
];
const rewrittenPlatforms = platforms.map(({ id, name }) => ({
id,
name: rewrites[name] ?? name // Use rewritten name, if present, otherwise use old name.
}));
console.log(rewrittenPlatforms);

Related

Is there any way to filter objects from array of objects that should include all selected values in javascript

Here i have skills array and employees array and i am trying to get the employees that includes all the skills that are included in skills array using reduce, filter or find method. I am trying to stored the filtered employees in filteredItems but got stuck in it.
filteredItems = Skills?.length>0 ?
Employees?.filter((item) => {
return item.Skills.find((ele) => {
return Skills.find((el) => {
if(el.value === ele.id){
return ele
}
})
})
}) : []
Below are the arrays mentioned.
Skills Array
[
{
"value": 6,
"label": "Marketing"
},
{
"value": 20,
"label": "Golang"
}
]
Employees Array
[
{
"name": "Hassan",
"id": 56,
"Skills": [
{
"id": 20,
"name": "Golang",
},
],
},
{
"name": "Haroon",
"id": 95,
"Skills": [
{
"id": 6,
"name": "Marketing",
},
{
"id": 20,
"name": "Golang",
},
],
},
]
For example, in above scenario of arrays it should return employee of id of 95 not return employee of id 56 because it includes skills but not all that are mention in skills array.
I found it easier to first encapsulate an array of skill IDs to search for.
let skillIds = Skills.map(s => s.value);
Then I filtered and compared the end result to the length of the skill Ids array:
let filteredItems = Skills?.length > 0 ?
Employees?.filter(item => item.Skills.filter( s =>
skillIds.includes(s.id)).length==skillIds.length): []
let Skills = [{
"value": 6,
"label": "Marketing"
}, {
"value": 20,
"label": "Golang"
}]
let Employees = [{
"name": "Hassan",
"id": 56,
"Skills": [{
"id": 20,
"name": "Golang",
}],
}, {
"name": "Haroon",
"id": 95,
"Skills": [{
"id": 6,
"name": "Marketing",
},
{
"id": 20,
"name": "Golang",
},
],
}, ]
let skillIds = Skills.map(s => s.value);
let filteredItems = Skills?.length > 0 ?
Employees?.filter(item => item.Skills.filter( s => skillIds.includes(s.id)).length==skillIds.length): []
console.log(filteredItems)
You could create another property in the employees array.. call it "QUalified". Default it to true, then set it to false when the employee doesn't have a skill in the skills array.
let arSkills = [
{
"value": 6,
"label": "Marketing"
},
{
"value": 20,
"label": "Golang"
}
];
let arEmp = [
{
"name": "Hassan",
"id": 56,
"Skills": [
{
"id": 20,
"name": "Golang",
},
],
},
{
"name": "Haroon",
"id": 95,
"Skills": [
{
"id": 6,
"name": "Marketing",
},
{
"id": 20,
"name": "Golang",
},
],
},
];
arEmp.forEach(ele =>{
ele.Qualified = true;
let arTmp = [];
for(let {id} of ele.Skills)
arTmp.push(id)
for(let {value} of arSkills)
if(!arTmp.includes(value))
ele.Qualified = false
});
let arQual = arEmp.filter((ele) =>{
return ele.Qualified
});
console.log(arQual);

React - Filter Multidimensional array with another array

I want to return only matches results.
My array:
products: [
{
"id": 1,
"name": "Product 1",
"concepts": [
{
"id": 10,
"name": "Blabla"
},
{
"id": 15,
"name": "Zlazla"
}
]
},
{
"id": 2,
"name": "Product 2",
"concepts": [
{
"id": 14,
"name": "Gulagula"
},
{
"id": 15,
"name": "Zlazla"
}
]
}
]
I want to filter products which only have one of the concepts below.
concepts array:
['14', '15']
Couldn't solve this in an easy way.
You can try this way:
var products= [
{
"id": 1,
"name": "Product 1",
"concepts": [
{
"id": 10,
"name": "Blabla"
},
{
"id": 15,
"name": "Zlazla"
}
]
},
{
"id": 2,
"name": "Product 2",
"concepts": [
{
"id": 14,
"name": "Gulagula"
},
{
"id": 15,
"name": "Zlazla"
}
]
}
]
var products = products.filter((product) => product.concepts = product.concepts.filter( (x) => x.id == 14 || x.id == 15));
console.log(products);

Iterate nested objects dynamically and push the specific values into separate array using recursion

I am trying java script recursive function that return an array of values based on the key.
The nested JavaScript object has unknown depth. The function is working but the value are not returning properly ..I am getting only first iterated value while I am calling this recursive function from another function. But I can able to console and see the values in same function.
Here is My json
{
"id": 0,
"name": "Root Entity",
"children": [{
"id": 1,
"name": "REAT",
"children": [{
"id": 2,
"name": "Business",
"children": [{
"id": 3,
"name": "Region 1",
"children": [{
"id": 5,
"name": "Area 1",
"children": [
{
"dealerId": 14,
"name": "lead 1"
},
{
"dealerId": 15,
"name": "lead 2"
},
{
"dealerId": 16,
"name": "lead 3"
},
{
"dealerId": 17,
"name": "lead 4"
},
{
"dealerId": 18,
"name": "lead 5"
},
{
"dealerId": 19,
"name": "lead 6"
}, {
"dealerId": 20,
"name": "lead 7"
}],
"kpi_1_met": 0,
"lead_num": 0,
}, {
"id": 6,
"name": "Area 2",
"children": [{
"dealerId": 31
"name": "lead 1"
}]
}]
}]
}]
}]
}
Here is the recursion function I have tried
async function outputArray(output, leadInfo, req, res) {
let resoutput = output.children,
constructedArray = [],
obj = {};
// dealerName, entityList = await entityNames(req, res);
let leagueData = [];
resoutput.forEach((dataArray) => {
if (dataArray.hasOwnProperty('children') &&
dataArray.children instanceof Array &&
dataArray.children.length > 0) {
// console.log("================ dataArray.children", dataArray.children[0]['name']);
for (let i in dataArray.children) {
obj = { 'regionId': dataArray.children[i].id, 'region': dataArray.children[i].name};
outputArray(dataArray.children[i], leadInfo, req, res);
leagueData.push(obj);
// console.log("================ leagueData ===============", leagueData);
}
} else {
if (dataArray.hasOwnProperty('name'))
// console.log("================ else", dataArray.name);
}
});
// console.log("================ leagueData outside =============", leagueData);
return leagueData;
}
And I am calling the above recursive function in another function that is below
async function dataTable(output, leadInfo, req, res) {
let obj = {},
data = await outputArray(output, leadInfo, req, res, obj);
// here First Iterated data only coming
// console.log("data from data Table", data)
}
Output Should be
[
{ regionId: 3, areaId: 5, dealerId: 14, name: 'lead 1', region: 'Region 1', area: 'Area 1' },
{ regionId: 3, areaId: 5, dealerId: 31, name: 'lead 1', region: 'Region 1', area: 'Area 2' }
]
It should be populated based on the hierarchy of the tree
Kindly anyone please help me on this. I am trying hard to get it out.
This is might you are looking for
let a = {
"id": 0,
"name": "Root Entity",
"children": [{
"id": 1,
"name": "REAT",
"children": [{
"id": 2,
"name": "Business",
"children": [{
"id": 3,
"name": "Region 1",
"children": [{
"id": 5,
"name": "Area 1",
"children": [
{
"id": 14,
"name": "lead 1"
},
{
"id": 15,
"name": "lead 2"
},
{
"id": 16,
"name": "lead 3"
},
{
"id": 17,
"name": "lead 4"
},
{
"id": 18,
"name": "lead 5"
},
{
"id": 19,
"name": "lead 6"
}, {
"id": 20,
"name": "lead 7"
}],
"kpi_1_met": 0,
"lead_num": 0,
}, {
"id": 6,
"name": "Area 2",
"children": [{
"id": 31,
"name": "lead 1"
}]
}]
}]
}]
}]
}
function test(data) {
let response = [];
if (Array.isArray(data)) {
for (let o of data) {
response.push({ id: o.id, name: o.name });
if (o.hasOwnProperty('children') && o.children.length > 0) {
let child = test(o.children);
response = response.concat(child);
}
}
} else {
response.push({ id: data.id, name: data.name });
if (data.hasOwnProperty('children') && data.children.length > 0) {
let child = test(data.children);
response = response.concat(child);
}
}
return response;
}
let res = test(a);
console.log(res)
You should save result of recursive call
outputArray(dataArray.children[i], leadInfo, req, res);
I am not sure I get the question correctly. If you just want to iterate in the data and push that to an array the below code will help.
<script>
var data = {
"id": 0,
"name": "Root Entity",
"children": [{
"id": 1,
"name": "REAT",
"children": [{
"id": 2,
"name": "Business",
"children": [{
"id": 3,
"name": "Region 1",
"children": [{
"id": 5,
"name": "Area 1",
"children": [
{
"id": 14,
"name": "lead 1"
},
{
"id": 15,
"name": "lead 2"
},
{
"id": 16,
"name": "lead 3"
},
{
"id": 17,
"name": "lead 4"
},
{
"id": 18,
"name": "lead 5"
},
{
"id": 19,
"name": "lead 6"
}, {
"id": 20,
"name": "lead 7"
}],
"kpi_1_met": 0,
"lead_num": 0
}, {
"id": 6,
"name": "Area 2",
"children": [{
"id": 31,
"name": "lead 1"
}]
}]
}]
}]
}]
}
let leagueData = [];
function outputArray(output, leadInfo, req, res) {
let resoutput = output.children,
obj = { 'regionId': output.id, 'region': output.name};
leagueData.push(obj);
if (output.hasOwnProperty('children') &&
output.children instanceof Array &&
output.children.length > 0) {
for (let i in output.children) {
console.log("*************** leagueData ===============", output.children[i]);
outputArray(output.children[i], leadInfo, req, res);
}
}
}
function dataTable(output, leadInfo, req, res) {
let obj = {},
data = outputArray(output, leadInfo, req, res, obj);
// here First Iterated data only coming
console.log("data from data Table", leagueData)
}
dataTable(data,"","","");
</script>
It's not entirely clear to me if this is what you're looking for, but here is a technique that will flatten out the hierarchy, compressing ancestor name/ids into properties of the leaf nodes:
const nameToKey = (name) =>
name .replace(/\s*\d+$/, '') .toLowerCase ()
const flattenHierarchy = (node, desc = {}, {name, id, children} = node) =>
children && children .length > 0
? children .flatMap (child => flattenHierarchy (child, {
...desc,
[nameToKey (name)]: name,
[nameToKey (name) + 'Id']: id
}))
: [{...desc, ...node}]
const data = {"children": [{"children": [{"children": [{"children": [{"children": [{"dealerId": 14, "name": "lead 1"}, {"dealerId": 15, "name": "lead 2"}, {"dealerId": 16, "name": "lead 3"}, {"dealerId": 17, "name": "lead 4"}, {"dealerId": 18, "name": "lead 5"}, {"dealerId": 19, "name": "lead 6"}, {"dealerId": 20, "name": "lead 7"}], "id": 5, "kpi_1_met": 0, "lead_num": 0, "name": "Area 1"}, {"children": [{"dealerId": 31, "name": "lead 1"}], "id": 6, "name": "Area 2"}], "id": 3, "name": "Region 1"}], "id": 2, "name": "Business"}], "id": 1, "name": "REAT"}], "id": 0, "name": "Root Entity"}
console .log (flattenHierarchy (data))
This generates an array of objects that look like this:
{
"root entity": "Root Entity",
"root entityId": 0,
"reat": "REAT",
"reatId": 1,
"business": "Business",
"businessId": 2,
"region": "Region 1",
"regionId": 3,
"area": "Area 1",
"areaId": 5,
"dealerId": 14,
"name": "lead 1"
}
In the base case, when we're at a leaf node in the children -> children -> children hierarchy, we return the object we've built up with all of the leaf node's properties appended to it. If we're not on a leaf, then we append the current name/id property to our working object, and recursively call the function on each child using this enhanced working object, then flatMap their results into a single array.
This does not entirely match your suggested output. Firstly, there are more results, one for each leaf node in your input. I'm guessing that this is fine, that you were just providing samples and not the full expected result. If not, by what criteria do you choose the nodes to return? Secondly, there are several additional properties from the hierarchy included here, things like reatId and root entity. If you don't want these in the output, how do you decide to exclude them?
Finally, although I took a stab at converting the names into useful keys, it's guesswork, and it feels off. Transforming a string data value to an object key worries me; but perhaps it's just what you want.

How to get data from nested arrays in array object

I have an object array like this
array = {
"microservices": [
{
"id": 1,
"permissions": [
{
"id": 65,
"name": "Default permission"
},
{
"id": 64,
"name": "Super user Access"
}
]
},
{
"id": 2,
"permissions": []
},
{
"id": 3,
"permissions": [
{
"id": 18,
"name": "Script: Update"
},
{
"id": 15,
"name": "Application: Delete"
},
{
"id": 9,
"name": "Workspace: Create"
}
]
}
]
}
from microservices array I only want to get "permissions" arrays and stores to a new variable, I searched for it but not get any relevant solution, thanks in advance
You could use the map operator and fetch that specific property alone. Please check the below JS example.
const array = {
"microservices": [{
"id": 1,
"permissions": [{
"id": 65,
"name": "Default permission"
},
{
"id": 64,
"name": "Super user Access"
}
]
},
{
"id": 2,
"permissions": []
},
{
"id": 3,
"permissions": [{
"id": 18,
"name": "Script: Update"
},
{
"id": 15,
"name": "Application: Delete"
},
{
"id": 9,
"name": "Workspace: Create"
}
]
}
]
}
const output = []
array.microservices.map(function(x) {
output.push(...x.permissions);
})
console.log(output);
Simply you have to iterate the json object as follows. New array "Permissions" will return your data.
getPermissions(){
this.array.microservices.forEach(element => {
element.permissions.forEach(ele => {
this.permissions.push(ele);
});
});
console.log(this.permissions);
}
In advance You can use .map operator also..
This is not a specific Angular or Typescript question, but you can do it like this
const whatYouNeed = array.microservices.reduce((sum, item) => {
sum.push(item.permissions);
return sum;
}, []);
or if you want it to be a single level:
const whatYouNeed = array.microservices.reduce((sum, item) => {
sum = sum.concat(item.permissions);
return sum;
}, []);
Since you want a single array of all permissions, this would be the cleanest approach. Read about flatMap here
const permissions = array.microservices.flatMap(i => i.permissions)
console.log(permissions);
Use a polyfill for browser support. Available in the above link.
You can use ES6 map.
const permissionsArrays = array.microservices.map(microservice => microservice.permissions)
First you have an object which contains an array not an actual array. But let's ignore that for now.
array = {
"microservices": [
{
"id": 1,
"permissions": [
{
"id": 65,
"name": "Default permission"
},
{
"id": 64,
"name": "Super user Access"
}
]
},
{
"id": 2,
"permissions": []
},
{
"id": 3,
"permissions": [
{
"id": 18,
"name": "Script: Update"
},
{
"id": 15,
"name": "Application: Delete"
},
{
"id": 9,
"name": "Workspace: Create"
}
]
}
]
}
const permissions = array.microservices.map(item => {
return item.permissions;
});
So assuming that, this is the json data that your recevice:
{
"microservices": [
{
"id": 1,
"permissions": [
{
"id": 65,
"name": "Default permission"
},
{
"id": 64,
"name": "Super user Access"
}
]
},
{
"id": 2,
"permissions": []
},
{
"id": 3,
"permissions": [
{
"id": 18,
"name": "Script: Update"
},
{
"id": 15,
"name": "Application: Delete"
},
{
"id": 9,
"name": "Workspace: Create"
}
]
}
]
}
Just create an interface, to use intellisense:
export interface Microservice {
microservices?: (MicroservicesEntity)[] | null;
}
export interface MicroservicesEntity {
id: number;
permissions?: (PermissionsEntity | null)[] | null;
}
export interface PermissionsEntity {
id: number;
name: string;
}
In that way you can gain the help of intellisense, so access the data by reference the interface to the json data:
data: Microservice;
After that use map to gain the array of permission

Adding key in an array by finding a value AngularJS

I am trying to add an extra key in a JSON array by searching any key value.
Example JSON:-
[
{
"$id": "2025",
"ID": 41,
"Name": "APPLE"
},
{
"$id": "2026",
"ID": 45,
"Name": "MANGO"
},
{
"$id": "2027",
"ID": 48,
"Name": "GUAVA"
}
]
Suppose I have to add a new key pair example "Price": 50 after "Name": "MANGO" or by finding ID ID": 45. So my expected new JSON will be :-
[
{
"$id": "2025",
"ID": 41,
"Name": "APPLE"
},
{
"$id": "2026",
"ID": 45,
"Name": "MANGO",
"Price": 50
},
{
"$id": "2027",
"ID": 48,
"Name": "GUAVA"
}
]
It must add on the object related to matched search key.
So, I am not able to find out any function related to the issue.
You can run a loop and check the condition and then add a property to an object. Here is a running code snippet. You can read here more about JavaScript Objects
var myarray = [
{
"$id": "2025",
"ID": 41,
"Name": "APPLE"
},
{
"$id": "2026",
"ID": 45,
"Name": "MANGO"
},
{
"$id": "2027",
"ID": 48,
"Name": "GUAVA"
}
]
for(var i=0;i<myarray.length;i++){
if(myarray[i].$id === "2025" || myarray[i].Name === "APPLE"){
var data = myarray[i];
data.price = 50
}
}
console.log(myarray)
You can use array#find to compare the ID. Then based that you can add Price key to the object.
let arr = [ { "$id": "2025", "ID": 41, "Name": "APPLE" }, { "$id": "2026", "ID": 45, "Name": "MANGO" }, { "$id": "2027", "ID": 48, "Name": "GUAVA" } ],
id = 45,
obj = arr.find(({ID}) => ID === id);
if(obj);
obj.Price = 50;
console.log(arr);
You can try with:
data.find(item => item.ID === 45).price = 50;
To cover the case if item is not available:
(data.find(item => item.ID === 45) || {}).price = 50;

Categories

Resources