How to update environment variable key name dynamically using NodeJS - javascript

I'm reading the environment variables (Key & Value) dynamically and forming below array:
commands: [
{
name: 'PRODUCT_NAME',
value: 'iPhone'
},
{
name: 'PRODUCT_PRICE',
value: '1232'
},
{
name: 'PRODUCT_TYPE',
value: 'Electronics'
},
{
name: 'PRODUCT_ID',
value: 'SKU29389438'
},
{
name: 'LOG_ENABLED',
value: 'TRUE'
},
]
I want to update the key name for these two properties dynamically PRODUCT_TYPE -> myapp.property.type.event and PRODUCT_ID -> myapp.property.product.enabled
Final output should look like this:
commands: [
{
name: 'PRODUCT_NAME',
value: 'iPhone'
},
{
name: 'PRODUCT_PRICE',
value: '1232'
},
{
name: 'myapp.property.type.event',
value: 'Electronics'
},
{
name: 'myapp.property.product.enabled',
value: 'SKU29389438'
},
{
name: 'LOG_ENABLED',
value: 'TRUE'
},
]
Please find my product.js code below:
const commands = (Object.entries(process.env).map(([key, value]) => ({ name: key, value })))
console.log("commands : ", commands);
I'm new to Nodejs, can someone please help how can I update these two key dynamically and form the final array?
Your help would be greatly appreciated!

1) You can just loop over and change the name as:
const obj = {
commands: [
{
name: "PRODUCT_NAME",
value: "iPhone",
},
{
name: "PRODUCT_PRICE",
value: "1232",
},
{
name: "PRODUCT_TYPE",
value: "Electronics",
},
{
name: "PRODUCT_ID",
value: "SKU29389438",
},
{
name: "LOG_ENABLED",
value: "TRUE",
},
],
};
obj.commands.forEach((o) => {
if (o.name === "PRODUCT_TYPE") o.name = "myapp.property.type.event";
if (o.name === "PRODUCT_ID") o.name = "myapp.property.product.enabled";
});
console.log(obj.commands);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
2) You can also do as :
one-liner
obj.commands.forEach((o) => (o.name = changes[o.name] ?? o.name));
const obj = {
commands: [{
name: "PRODUCT_NAME",
value: "iPhone",
},
{
name: "PRODUCT_PRICE",
value: "1232",
},
{
name: "PRODUCT_TYPE",
value: "Electronics",
},
{
name: "PRODUCT_ID",
value: "SKU29389438",
},
{
name: "LOG_ENABLED",
value: "TRUE",
},
],
};
const changes = {
PRODUCT_TYPE: "myapp.property.type.event",
PRODUCT_ID: "myapp.property.product.enabled",
};
obj.commands.forEach((o) => {
if (changes[o.name]) o.name = changes[o.name];
});
console.log(obj.commands);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related

Extract array from javascript object

I have below javascript object - (named Division)
I want to extract only SubDivs from the array
I tried : -
const division = [{
Name: "DivName1",
Value: "DivValue1",
SubDivision: {
Name: "SubDiv1",
Value: "SubDiv1"
}
},
{
Name: "DivName2",
Value: "DivValue2",
SubDivision: [{
Name: "SubDiv2",
Value: "SubDiv2"
},
{
Name: "SubDiv3",
Value: "SubDiv3"
}
]
}
]
var subDivs = division.map(x => x.SubDivision);
console.log(subDivs)
But this is not giving me array in format -
[{
Name:"SubDiv1",
Value:"SubDiv1"
},
{
Name:"SubDiv2",
Value:"SubDiv2"
},
{
Name:"SubDiv3",
Value:"SubDiv3"
}]
You can use flatMap for that
const division = [{
Name: "DivName1",
Value: "DivValue1",
SubDivision: [{
Name: "SubDiv1",
Value: "SubDiv1"
}]
},
{
Name: "DivName2",
Value: "DivValue2",
SubDivision: [{
Name: "SubDiv2",
Value: "SubDiv2"
},
{
Name: "SubDiv3",
Value: "SubDiv3"
}
]
}
]
const subdivision = division.flatMap(d => d.SubDivision)
console.log(subdivision)
Given your example, all you need to do is call flat on the mapped array:
var subDivs= division.map(x=>x.SubDivision).flat();
Working example:
const division = [{
Name: "DivName1",
Value: "DivValue1",
SubDivision: [{
Name: "SubDiv1",
Value: "SubDiv1"
}
]},
{
Name: "DivName2",
Value: "DivValue2",
SubDivision: [{
Name: "SubDiv2",
Value: "SubDiv2"
},
{
Name: "SubDiv3",
Value: "SubDiv3"
}
]
}
]
var subDivs= division.map(x=>x.SubDivision).flat();
console.log(subDivs)

Transform Object attribute to array of object

I want to merge Array of ObjectA containing ObjectB attribute by ObjectA attribute.
For example :
let myArray = [
{ name: 'Jeu', series: { name: 'testA', value: '89' } },
{ name: 'Dim', series: { name: 'testB', value: '490' } },
{ name: 'Dim', series: { name: 'testC', value: '978' } }
]
And I would like to transform it to
[
{ name: 'Jeu', series: { name: 'testA', value: '89' } },
{ name: 'Dim', series: [{ name: 'testB', value: '490' },{ name: 'testC', value: '978' } ] }
]
Am I able to do that with a simple reduce/map loop ?
You can first use reduce (with some spread syntax) to build an object that maps unique names and objects in the format you want to have, grouping series by name. Then, you can simply get the values from this object.
const myArray = [
{ name: 'Jeu', series: { name: 'testA', value: '89' } },
{ name: 'Dim', series: { name: 'testB', value: '490' } },
{ name: 'Dim', series: { name: 'testC', value: '978' } }
];
const map = myArray.reduce(
(acc, curr) => ({
...acc,
[curr.name]: {
name: curr.name,
series: acc[curr.name]
? [...acc[curr.name].series, curr.series]
: [curr.series]
}
}),
{}
);
const output = Object.values(map);
console.log(output);

How to convert json to tree array in JS?

I would like to convert this json / object to this specific structure below to allow me to use a treeList component.
I've tried to build a recursive function but I didn't find the solution yet.
Thanks for your help
const data = {
parent1: {
child1: { bar: "1" },
child2: "2"
},
parent2: {
child1: "1"
}
}
to
const treeData = [
{
title: "parent1",
key: "parent1",
children: [
{
title: "child1",
key: "child1",
children: [{ title: "bar", key: "bar", value: "1" }]
},
{
title: "child2",
key: "child2",
value: "2"
}
],
},
{
title: "parent2",
key: "parent2",
children: [
{
title: "child1",
key: "child1",
value: "1"
}
]
}
]
You could take an iterative and recursive approach.
function getNodes(object) {
return Object
.entries(object)
.map(([key, value]) => value && typeof value === 'object'
? { title: key, key, children: getNodes(value) }
: { title: key, key, value }
);
}
const data = { parent1: { child1: { bar: "1" }, child2: "2" }, parent2: { child1: "1" } },
result = getNodes(data);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
just share sample, a little different from yours. But it give you a hint with recursive function.
https://jsfiddle.net/segansoft/7bdxmys4/1/
function getNestedChildren(arr, parent) {
var out = []
for (var i in arr) {
if (arr[i].parent == parent) {
var children = getNestedChildren(arr, arr[i].id)
if (children.length) {
arr[i].children = children
}
out.push(arr[i])
}
}
return out
}
var flat = [{
id: 1,
title: 'hello',
parent: 0
},
{
id: 2,
title: 'hello',
parent: 0
},
{
id: 3,
title: 'hello',
parent: 1
},
{
id: 4,
title: 'hello',
parent: 3
},
{
id: 5,
title: 'hello',
parent: 4
},
{
id: 6,
title: 'hello',
parent: 4
},
{
id: 7,
title: 'hello',
parent: 3
},
{
id: 8,
title: 'hello',
parent: 2
}
]
var nested = getNestedChildren(flat, 0)
document.write('<pre>' + JSON.stringify(nested, 0, 4) + '</pre>');

Setting array keys dynamically based on length

Given an array in this format:
[
[{
name: "name",
value: "My-name"
},
{
name: "qty",
value: "1"
},
{
name: "url",
value: "test.com"
},
{
name: "comment",
value: "my-comment"
}
],
[{
name: "name",
value: "My-name2"
},
{
name: "qty",
value: "3"
},
{
name: "url",
value: "test2.com"
}
],
[{
name: "name",
value: "My-name3"
},
{
name: "qty",
value: "1"
},
{
name: "url",
value: "test3.com"
},
{
name: "comment",
value: "my-comment3"
}
]
]
I'm looking to switch that to:
[
[
{ name: "My-name" },
{ qty: "1" },
{ url: "test.com" },
{ comment: "my-comment", }
],[
{ name: "My-name2" },
{ qty: "3" },
{ url: "test2.com",
],[
{ name: "My-name3", },
{ qty: "1", },
{ url: "test3.com", },
{ comment: "my-comment3", }
]
]
In other words, swapping out the array keys but maintaining the object structure within each array element.
I've tried looping over each element and can swap the keys out using something like:
newArray[iCount][item.name] = item.value;
However I'm then struggling to preserve the object order. Note that the comment field may or may not appear in the object.
With Array.map() function:
var arr = [
[{name:"name",value:"My-name"},{name:"qty",value:"1"},{name:"url",value:"test.com"},{name:"comment",value:"my-comment"}],
[{name:"name",value:"My-name2"},{name:"qty",value:"3"},{name:"url",value:"test2.com"}],
[{name:"name",value:"My-name3"},{name:"qty",value:"1"},{name:"url",value:"test3.com"},{name:"comment",value:"my-comment3"}]
],
result = arr.map(function(a){
return a.map(function(obj){
var o = {};
o[obj.name] = obj.value
return o;
});
});
console.log(result);
Check my moreBetterOutput value. I think will be better.
If you still need a result like your example in the question then you can check output value.
const input = [
[
{
name:"name",
value:"My-name"
},
{
name:"qty",
value:"1"
},
{
name:"url",
value:"test.com"
},
{
name:"comment",
value:"my-comment"
}
],
[
{
name:"name",
value:"My-name2"
},
{
name:"qty",
value:"3"
},
{
name:"url",
value:"test2.com"
}
],
[
{
name:"name",
value:"My-name3"
},
{
name:"qty",
value:"1"
},
{
name:"url",
value:"test3.com"
},
{
name:"comment",
value:"my-comment3"
}
]
]
const output = input.map(arr => arr.map(obj => ({[obj.name]: obj.value})))
const moreBetterOutput = output.map(arr => arr.reduce((acc, item, index) => {
acc[Object.keys(item)[0]] = item[Object.keys(item)[0]];
return acc;
}, {}) )
//console.log(output);
console.log(moreBetterOutput);
Another map function:
const result = array.map( subarray =>
Object.assign(...subarray.map( ({name, value}) => ({ [name] : value }) ))
);

Concat array from Object from Array

I'm currently trying to retrieve a list of metadata stored as an array, inside an object, inside an array. Here's a better explanatory example:
[
{
name: 'test',
metadata: [
{
name: 'Author',
value: 'foo'
},
{
name: 'Creator',
value: 'foo'
}
]
},
{
name: 'otherTest',
metadata: [
{
name: 'Created',
value: 'foo'
},
{
name: 'Date',
value: 'foo'
}
]
},
{
name: 'finalTest'
}
]
Now, my objective is to retrieve a list of metadata (by their name) without redundancy. I think that .map() is the key to success but I can't find how to do it in a short way, actually my code is composed 2 for and 3 if, and I feel dirty to do that.
The expected input is: ['Author', 'Creator', 'Created', 'Date']
I'm developping in Typescript, if that can help for some function.
You can use reduce() and then map() to return array of names.
var data = [{"name":"test","metadata":[{"name":"Author","value":"foo"},{"name":"Creator","value":"foo"}]},{"name":"otherTest","metadata":[{"name":"Created","value":"foo"},{"name":"Date","value":"foo"}]},{"name":"finalTest"}]
var result = [...new Set(data.reduce(function(r, o) {
if (o.metadata) r = r.concat(o.metadata.map(e => e.name))
return r
}, []))];
console.log(result)
You could use Set for unique names.
var data = [{ name: 'test', metadata: [{ name: 'Author', value: 'foo' }, { name: 'Creator', value: 'foo' }] }, { name: 'otherTest', metadata: [{ name: 'Created', value: 'foo' }, { name: 'Date', value: 'foo' }] }, { name: 'finalTest' }],
names = new Set;
data.forEach(a => (a.metadata || []).forEach(m => names.add(m.name)));
console.log([...names]);
.as-console-wrapper { max-height: 100% !important; top: 0; }
var data = [{"name":"test","metadata":[{"name":"Author","value":"foo"},{"name":"Creator","value":"foo"}]},{"name":"otherTest","metadata":[{"name":"Created","value":"foo"},{"name":"Date","value":"foo"}]},{"name":"finalTest"}]
data
.filter(function(obj){return obj.metadata != undefined})
.map(function(obj){return obj.metadata})
.reduce(function(a,b){return a.concat(b)},[])
.map(function(obj){return obj.name})
A hand to hand Array.prototype.reduce() and Array.prototype.map() should do it as follows;
var arr = [
{
name: 'test',
metadata: [
{
name: 'Author',
value: 'foo'
},
{
name: 'Creator',
value: 'foo'
}
]
},
{
name: 'otherTest',
metadata: [
{
name: 'Created',
value: 'foo'
},
{
name: 'Date',
value: 'foo'
}
]
},
{
name: 'finalTest'
}
];
result = arr.reduce((p,c) => c.metadata ? p.concat(c.metadata.map(e => e.name))
: p, []);
console.log(result);

Categories

Resources