How to convert string array into custom nested object - javascript

I am trying to convert a string array into single nested object suggest a best way to do that,
For example, If I had a single element in an array
Input:
var keys = ["A"];
It should be like this,
Output:
{
and: {
tags: {
contains: "A"
}
}
}
And if I add a second element for example,
Input:
var keys = ["A","B"];
It should add as a nested object like this,
Output:
{
and: {
tags: {
contains: "A"
},
and: {
tags: {
contains: "B"
}
}
}
}

You can try to use Array.reduceRight function(Thanks Drew Reese's suggestion):
const nest = arr => arr.reduceRight((acc, cur) => ({ and: { tags: { contains: cur }, ...acc } }), {});
console.log(nest(['A']));
console.log(nest(['A', 'B']));
console.log(nest(['A', 'B', 'C']));

Related

How can I return a dynamic data using methods in JavaScript?

I am having a variable that needs to return data according to the array of objects.
There are 3 dummies which are dynamic in such a way -->
Example:
dummy1_A, dummy1_B, dummy1_C, ...
dummy2_A, dummy2_B, dummy2_C, ...
dummy3_A, dummy3_B, dummy3_C, ...
I want to set 'fieldName' and 'text' while returning.
And this is my code. I have to use JSON.stringify to show the data I need
Also, I am using map method
let a1 = [
{
dummy1_A: 0.5526714707565221,
dummy2_A: 0.5526714707565223,
dummy3_A: 0.5526714707565224,
dummy1_B: 0.5028423429150607,
dummy2_B: 0.5028423429150605,
dummy3_B: 0.5028423429150604,
},
{
dummy1_A: 0.542947572819916,
dummy2_A: 0.4965857885945633,
dummy3_A: 0.4965857885945677,
dummy1_B: 0.4470431086251489,
dummy2_B: 0.3785646261205342,
dummy3_B: 0.3785646261205345,
},
];
let a2 = a1.map((x, i) => {
let seqStr = String(a1.entries); // I need some help here
return {
text: seqStr,
fieldName: seqStr,
};
});
// output
[
{ text: 'dummy1_A', fieldName: 'A' },
{ text: 'dummy2_A', fieldName: 'A' },
{ text: 'dummy1_B', fieldName: 'B' },
{ text: 'dummy2_B', fieldName: 'B' },
];
We can also use forEach but this also need more logic
a1.forEach(obj => {
const key = Object.keys(obj)[0];
const newKey = key[key.length - 1];
obj[newKey] = obj[key];
delete obj[key];
});
I have used console.log(JSON.stringify(a2)); Though I was using map but not got such result
let newHeaders1 = a1.map( i => {
return {
text: i,
fieldName: 'dummy1_'+i,
width: 110
};
});
Use this and create 2 more arrays with 2 and 3 respectively.
Then consolidated all the variable in an array using concat or spread operator

Find Index from Mapped Objects

Desired output will be like, I want to find last and first index. I'm having trouble in handling this. I'm not be able to get the index from this objects.
{
'13-2-2022' =>[
{
"name":"abc"
"date":"13-2-2022"
},
{
"name":"xyz"
"date":"13-2-2022"
}
]
'15-2-2022' =>[
{
"name":"azx"
"date":"15-2-2022"
},
{
"name":"qwe"
"date":"15-2-2022"
}
]
'16-2-2022' =>[
{
"name":"azx"
"date":"16-2-2022"
},
{
"name":"qwe"
"date":"16-2-2022"
}
{
"name":"qpe"
"date":"16-2-2022"
}
]
}
You can get the object keys with Object.keys function.
const keys = Object.keys(myMap);
const first = keys[0];
const last = keys[keys.length-1];

Get matching values of two objects

I have an object inboundTransfer which contains an unknown number of keys. I would like to get all values from the itemNumbersList properties which match the values on an array Object.keys(selectedItems). The data that I receive looks a little something like this:
const selectedItems = {
'nameX': {
propert1: 'value1',
property2: 'value2,
...
}
},
'nameY': {
...
},
'nameT': {
...
}
const inboundTransfers = {
0: {
property1: 'value1',
itemNumbersList: ['nameX', 'nameY', 'nameZ'],
},
1: {
property2: 'value2',
itemNumbersList: ['nameK', 'nameJ', 'nameT']
},
...
}
const isOnTransferlist = Object.keys(inboundTransfers)
.map((transfer) => Object.values(inboundTransfers[transfer].itemNumbersList)
.some((item) => Object.keys(selectedItems)
.indexOf(item) >= 0));
Obviously, I currently only check if the value is on both lists or not. Ideally, I would like to get the value itself. How could I achieve that? I tried using .filter instead of map but with no success.
Any help is much appreciated!
I implemented this function and I test it, it works well.
function match() {
const selectedItems = {
a: "a1",
b: "b1",
};
const inboundTransfers = {
0: {
items: ["a", "b"],
},
1: {
items: ["c", "b"],
},
};
const capturedValues = []; // founded items store
[...Object.keys(selectedItems)].forEach((arrKey) => {
for (let [key, items] of Object.entries(inboundTransfers)) {
Object.values(items).forEach((item) => {
item.forEach((i) => {
if (i === arrKey) {
capturedValues.push(i);
}
});
});
}
});
// Remove redundant values
console.log([...new Set(capturedValues)]);
}
I found a way that works, but it's not very elegant, I guess:
const list = [];
Object.keys(inboundTransfers)
.forEach((transfer) => {
Object.values(inboundTransfers[transfer].itemNumbersList)
.forEach((item) => {
if (Object.keys(selectedItems).includes(item)) {
list.push(item);
}
});
});

javascript object.assign for a only one property without making a copy

lets say we have object a
a = {
prop1:"something",
schema:{
array:[array of object]
}
}
and b is
b = {
array:[array of object]
}
and in the object arrays they have pretty much the same object with different values. I want to create a new object with a.schema updated from b with object.assign.
so I wrote something like Object.assign({},a.schema,b) and it returns me this
{
schema:
{
array:[array of object]
}
}
.But I don't want to create a copy of a and then copy this schema into the newly created copy of a.
I want this
newObject = {
prop1:"something",
schema:{
array:[array of object from b]
}
}
I want to create a new object which look just like a in a single Object.assign , is that possible?
This is an example of what you can do:
x = {a:1,b:[1,2,3}}
y = {c:[4,5,6]}
z=Object.assign({},{prop1:x.a},{shcema:y.c})
If it's all right to use the spread syntax, you can do this:
const a = {
prop1: 'something',
schema: {
array: [
{
aprop: 'prop',
},
],
},
};
const b = {
array: [
{
bprop: 'test',
},
{
bprop: 'test2',
},
],
};
const updated = {
...a,
schema: b,
};
console.log(updated);

Fastest way to find if an array of object contains one of the tags

I have an array of objects, with each object containing a property tags that contains an array of strings
let item = {
tags: [String],
name: String
};
let queue = [item1, item2, ...];
I want to know find all items that contain a specific tag(s). The brute force would be 2 for-loops:
function findTags(tags) {
let results = [];
queue.forEach(function (item) {
tags.forEach(function (tag) {
if (item.tags.indexOf(tag) !== -1) {
results.push(item);
}
});
});
return results;
}
Is there a better than O(N^2) way?
Use Set or just Object to store tags so you don't need to iterate tags array to search a tag.
Use Array#some to stop iterate as soon as a match is found.
Since you are filtering the array, use Array#filter
var tagsObj = Object.create(null);
tags.forEach(function (tag) {
tagsObj[tag] = true;
});
return queue.filter(function (item) {
return item.tags.some(function (tag) {
return tagsObj[tag];
});
});
I would like to implement one for getFirst and one for getAll function.
var queue = [
{
tags: ["tag01","tag02","tag03"],
name: "name01"
},
{
tags: ["tag04","tag05","tag06"],
name: "name02"
},
{
tags: ["tag02","tag04","tag06"],
name: "name03"
},
{
tags: ["tag01","tag03","tag05"],
name: "name04"
},
],
getFirst = (...tags) => queue.find( o => tags.some( t => o.tags.includes(t))),
getAll = (...tags) => queue.reduce((p,o) => tags.some( t => o.tags.includes(t)) ? p.concat(o) : p ,[]);
document.write("<pre> Result for getFirst:\n" + JSON.stringify(getFirst("tag04","tag02"),null,2) + "</pre>");
document.write("<pre> Result for getAll:\n" + JSON.stringify(getAll("tag04","tag02"),null,2) + "</pre>");

Categories

Resources