Get bad values inside a loop - javascript

I've got a method for generate url
But I have a little problem when I'm adding the condition if/else, he returns me only the first value and not all
This is my code :
public generateUrl(components: any, versions: any) {
const keys: any[] = Object.keys(components); //['toto','titi','tata','tutu']
for (const component of keys) {
const versions = components[component].artifacts.map((arti) => {
return {
component: arti.name,
type: arti.type,
version: versions[arti.name],
};
});
console.log(versions); // Display only the first one and not all
//[ { component: 'toto',
// type: 'npm',
// version: '1' } ]
for (const i in versions) {
const v = versions[i];
// here i'm adding the confition
if (v.type === "jar") {
const urlTest =
v.component +
"/" +
v.version +
".jar"
return urlTest;
} else if (v.type === "npm") {
const urlTest =
v.component +
"/" +
v.version +
".npm"
return urlTest;
}
} else if (v.type === "rpm") {
const urlTest =
v.component +
"/" +
v.version +
".rpm"
return urlTest;
}
}
}
}
}
I need to retrieve all values and not only the first one.
THanks for your help

Use Array.prototype.reduce to accumulate your values which match up to your type, instead of returning after match.
Also the for-in loop is to enumerate over enumerable object properties of a object, if I am not mistaken then versions is an array.
Working example below -
const data = [
{
component: 'toto',
type: 'npm',
version: '1'
},
{
component: 'tata',
type: 'jar',
version: '2'
},
{
component: 'titi',
type: 'rpm',
version: '3'
}
];
const types = ['npm', 'jar', 'rpm'];
const testUrls = data.reduce((acc, { component, type, version }) => {
if (types.includes(type)) {
acc.push(`${component}/${version}.${type}`);
}
return acc;
}, []);
console.log(testUrls);

like #Bergi said
That's because you return from the first iteration of the loop.
else you can try something like that, by using reduce:
Working example:
type Component = {
artifacts: any[];
};
type Version = {
[key: string]: string;
}
class Test {
public static GenerateUrl(components: Component[], versions: Version) {
return components.reduce((acc: any, { artifacts }) => {
return artifacts.reduce((acc, { type, name }) => {
acc.push(`${name}#${versions[name]}.${type}`);
return acc.flat();
}, acc);
}, []);
}
};
const versions: any = {
"titi": "1.0.0",
"toto": "1.8.1",
"tata": "1.2.5"
}
const components = [
{
artifacts: [
{
type: "jar",
name: "titi"
},
{
type: "npm",
name: "titi"
},
{
type: "rpm",
name: "toto"
},
{
type: "rpm",
name: "tata"
}
]
}
]
console.log(Test.GenerateUrl(components, versions)); // ["titi#1.0.0.jar","titi#1.0.0.npm","toto#1.8.1.rpm","tata#1.2.5.rpm"]

Related

Node.js - How to merge objects inside an array based on condition?

In Node.js, I have 3 sets of data like
[
{
"userId":"54c7f3ef-64d4-40de-8100-d2ec81e8aaf3",
"dailyData":159392.235451,
"dailyDataInUSC":255.284807
}
]
and
[
{
"userId":"54c7f3ef-64d4-40de-8100-d2ec81e8aaf3",
"monthlyData":159392.235451,
"monthlyDataInUSC":255.284807
},
{
"userId":"23fs6fds3-34k4-17de-3123-d2ec81e8aaf3",
"monthlyData":349392.455451,
"monthlyDataInUSC":655.234807
}
]
and
[
{
"userId":"54c7f3ef-64d4-40de-8100-d2ec81e8aaf3",
"threeMonthsData":159392.235451,
"threeMonthsDataInUSC":255.284807
},
{
"userId":"23fs6fds3-34k4-17de-3123-d2ec81e8aaf3",
"threeMonthsData":349392.455451,
"threeMonthsDataInUSC":655.234807
},
{
"userId":"34sdf34-67j4-54nd-6763-d2ec81e8aaf3",
"threeMonthsData":6789392.455451,
"threeMonthsDataInUSC":905.655807
}
]
How can I combine this to one object based on userId(filter) inside an array.
Eg, output should be like
[
{
"userId":"54c7f3ef-64d4-40de-8100-d2ec81e8aaf3",
"dailyData":159392.235451,
"dailyDataInUSC":255.284807,
"monthlyData":159392.235451,
"monthlyDataInUSC":255.284807,
"threeMonthsData":159392.235451,
"threeMonthsDataInUSC":255.284807
}
]
Please help me to achieve this.
A combination of spread, reduce and findIndex can be used to solve the problem.
Combine the original arrays into a single array using the spread operator.
Use reduce to group the elements by key (in this case userId)
Something like this :
const dailyData = [{"userId":"54c7f3ef-64d4-40de-8100-d2ec81e8aaf3","dailyData":159392.235451,"dailyDataInUSC":255.284807}];
const monthlyData = [{"userId":"54c7f3ef-64d4-40de-8100-d2ec81e8aaf3","monthlyData":159392.235451,"monthlyDataInUSC":255.284807}, {"userId":"23fs6fds3-34k4-17de-3123-d2ec81e8aaf3","monthlyData":349392.455451,"monthlyDataInUSC":655.234807}]
const triMonthlyData = [{"userId":"54c7f3ef-64d4-40de-8100-d2ec81e8aaf3","threeMonthsData":159392.235451,"threeMonthsDataInUSC":255.284807}, {"userId":"23fs6fds3-34k4-17de-3123-d2ec81e8aaf3","threeMonthsData":349392.455451,"threeMonthsDataInUSC":655.234807}, {"userId":"34sdf34-67j4-54nd-6763-d2ec81e8aaf3","threeMonthsData":6789392.455451,"threeMonthsDataInUSC":905.655807}]
const combinedData = [...dailyData, ...monthlyData, ...triMonthlyData].reduce((mergedResult, curElement) => {
let matchingElementIdx = mergedResult.findIndex(ele => ele.userId === curElement.userId);
if (matchingElementIdx !== -1) {
mergedResult[matchingElementIdx] = {...mergedResult[matchingElementIdx], ...curElement};
} else {
mergedResult = [...mergedResult, curElement];
}
return mergedResult;
}, []);
console.log(combinedData);
const aa = () => {
let aa = [
{
userId: "54c7f3ef-64d4-40de-8100-d2ec81e8aaf3",
dailyData: 159392.235451,
dailyDataInUSC: 255.284807
}
];
let bb = [
{
userId: "54c7f3ef-64d4-40de-8100-d2ec81e8aaf3",
monthlyData: 159392.235451,
monthlyDataInUSC: 255.284807
},
{
userId: "23fs6fds3-34k4-17de-3123-d2ec81e8aaf3",
monthlyData: 349392.455451,
monthlyDataInUSC: 655.234807
}
];
let cc = [
{
userId: "54c7f3ef-64d4-40de-8100-d2ec81e8aaf3",
threeMonthsData: 159392.235451,
threeMonthsDataInUSC: 255.284807
},
{
userId: "23fs6fds3-34k4-17de-3123-d2ec81e8aaf3",
threeMonthsData: 349392.455451,
threeMonthsDataInUSC: 655.234807
},
{
userId: "34sdf34-67j4-54nd-6763-d2ec81e8aaf3",
threeMonthsData: 6789392.455451,
threeMonthsDataInUSC: 905.655807
}
];
let newArrObj = aa;
bb.forEach(item => {
let index = newArrObj.findIndex(item1 => item1.userId === item.userId);
if (index === -1) {
newArrObj = [...newArrObj, item];
} else {
newArrObj[index] = { ...newArrObj[index], ...item };
}
});
cc.forEach(item => {
let index = newArrObj.findIndex(item1 => item1.userId === item.userId);
if (index === -1) {
newArrObj = [...newArrObj, item];
} else {
newArrObj[index] = { ...newArrObj[index], ...item };
}
});
console.log(newArrObj);
};

Filtering json in javascript/typescript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have a json which as follows.
const d = {
data:{name:"name1", type:"abc"},
parent:{
data: {name:"parent1"},
parent:{
data: { name:"superparent1"},
parent: null
}
}
}
I want to get final output as "superparent1 / parent1 / name1" in an array. It should show the parent till the parent is null. How can I do that?
const d = {
data: {
name: "name1",
type: "abc"
},
parent: {
data: {
name: "parent1"
},
parent: {
data: {
name: "superparent1"
},
parent: null
}
}
}
const d1 = {
data: {
name: "name1",
type: "abc"
},
parent: {
data: {
name: "parent1"
},
parent: {
data: {
name: "superparent1"
},
parent: null
}
}
}
const resArr = [];
const formatFunc = (obj, arr) => {
if (obj) {
arr.push(obj.data.name);
return formatFunc(obj.parent, arr);
} else {
return "end";
}
}
const formatArrObj = (arr) => {
let iArr = [];
arr.map(item => {
formatFunc(item, iArr);
const str = iArr.reverse().join("/");
resArr.push(str);
iArr = [];
})
}
formatArrObj([d, d1]);
console.log(resArr);
This is what you were looking for or not?
Using a recursive method you can do something like this:
const filter = (a) => {
if(a.parent == null) {
return [a.data.name];
} else {
return [...filter(a.parent), a.data.name];
}
}
You can add appropriate typescript types where necessary.
Seems you need some code like this:
const output = [];
const getParent = (obj) => {
output.push(obj.data.name)
if (!obj.parent) {
return
}
return getParent(obj.parent)
}
getParent(d);
const formattedOutput = output.reverse().join(' / ');

Filtering logic for an array of object based on tabs

I have 3 tabs tabA, tabB, tabC and I have a common array of object which is being displayed in all these 3 tabs i.e
` data=[{value:"someValue (tabA) RO"},{value:"someValue (tabA) RW" },
{value:"someValue (tabB) RO"},{value:"someValue (tabB) RW" } ,
{value:"someValue (tabC) RO"},{value:"someValue (tabC) RW" }]`
filtering criteria is that when I am in tabA it should display both the tabA RO ,Rw values and only RO values of other tabs , same way if I am in tabB it should display both RO,RW values of tabB and only RO values of other tabs,same for the rest of the tabs . could somebody give me the logic.
Not sure what the data structure you are talking. I assume it looks like below.
const data = [
{ value: "tabAsomeValueRO (tabA) RO" },
{ value: "tabAsomeValueRW (tabA) RW" },
{ value: "tabBsomeValueRO (tabB) RO" },
{ value: "tabBsomeValueRW (tabB) RW" },
{ value: "tabCsomeValueRO (tabC) RO" },
{ value: "tabCsomeValueRW (tabC) RW" }
]
/**
* convert to the following object
{
tabA: {
RO: "tabAsomeValueRO",
RW: "tabAsomeValueRW",
},
tabB: {
RO: "tabBsomeValueRO",
RW: "tabBsomeValueRW",
},
tabC: {
RO: "tabCsomeValueRO",
RW: "tabCsomeValueRW",
}
}
*/
const regex = /([^ ]+) \(([^\)]+)\) ([^ ]+)/;
const newData = data.map(val => val.value).reduce((accum, val) => {
const arr = regex.exec(val);
const value = arr[1];
const tabName = arr[2];
const rValue = arr[3];
if (!accum[tabName]) {
accum[tabName] = {};
}
accum[tabName][rValue] = value;
return accum;
}, {});
function getValue(tab) {
return Object.keys(newData).reduce((accum, tmpTab) => {
const tmpTabValue = newData[tmpTab];
if (tmpTab === tab) {
accum.push(tmpTabValue.RO);
accum.push(tmpTabValue.RW);
}
else {
accum.push(tmpTabValue.RO);
}
return accum;
}, []);
}
console.log("tabA", getValue("tabA"));
console.log("tabB", getValue("tabB"));
console.log("tabC", getValue("tabC"));

How to fix my recursive function? I am receiving either an array of an array of data

I am trying to create a recursive function that will go through an object similar to a directory with subdirectories, and output the'file' objects in an array. However, it seems that i am getting an array of arrays rather than a simple array with the objects I am expecting to see...
The bottom of the code has some console.logs that return:
console.log(findEntry(repAll, '/first')); // ===> [ { name: '/first' }, [] ]
console.log(findEntry(repAll, '/second')); // ===> [ [ { name: '/second' }, { name: '/second' } ] ]
const repAll = {
file1: {
name: "/first"
},
SubDir: {
file2: {
name: "/second"
},
file3: {
name: "/second"
}
}
};
const req = {};
function findEntry(data, name) {
let x = [];
for (const value of Object.values(data)) {
// Is this a leaf node or a container?
if (value.name) {
// Leaf, return it if it's a match
if (value.name === name) {
x.push(value);
}
} else {
// Container, look inside it recursively
const entry = findEntry(value, name);
x.push(entry);
}
}
return x;
}
console.log('search: /first');
console.log(findEntry(repAll, '/first'));
console.log('search: /second');
console.log(findEntry(repAll, '/second'));
You could spread the result of findEntry instead of simply pushing the array.
const repAll = {
file1: {
name: "/first"
},
SubDir: {
file2: {
name: "/second"
},
file3: {
name: "/second"
}
}
};
const req = {};
function findEntry(data, name) {
let x = [];
for (const value of Object.values(data)) {
// Is this a leaf node or a container?
if (value.name) {
// Leaf, return it if it's a match
if (value.name === name) {
x.push(value);
}
} else {
// Container, look inside it recursively
x.push(...findEntry(value, name));
}
}
return x;
}
console.log('search: /first');
console.log(findEntry(repAll, '/first'));
console.log('search: /second');
console.log(findEntry(repAll, '/second'));
With your approach :
function findEntry(data, name,x) {
for (const value of Object.values(data)) {
// Is this a leaf node or a container?
if (value.name) {
// Leaf, return it if it's a match
if (value.name === name) {
x.push(value);
}
} else {
// Container, look inside it recursively
const entry = findEntry(value, name,x);
x.push(entry);
}
}
return x;
}
Now call it like this :
let arr=[];
console.log(findEntry(repAll, '/first',arr));

Verify if content key Json has exist using Vue

I want to know how to check if "novalue" exist
For example:
{
name: "maria",
city_id: "novalue"
....
}
How i do this in Vue?
Do it in <div v-if="condition"> or function?
In case you want to/can use ES7 features:
const containsKey = (obj, key ) => Object.keys(obj).includes(key);
Implementation example:
const someCoolObject = {name: 'Foo', lastName: 'Bar'};
const hasName = containsKey(someCoolObject, 'name');
const hasNickName = containsKey(someCoolObject, 'hasNickName');
console.log(hasName, hasNickName); // true, false
For Vue:
Component:
{
methods: {
containsKey(obj, key ) {
return Object.keys(obj).includes(key);
}
},
computed: {
hasName() {
return this.containsKey(this.someObject, 'name');
}
}
}
Template:
<div v-if="hasName"></div>

Categories

Resources