issue with spread operator in javascript - javascript

I want to rewrite an array and to get a new one at the final.
This is my code:
const arr = [
{
type:"Fiat", model:"500", color:"white"
},
{
type:"ford", model:"5300", color:"gray"
}
];
const newArr = arr.map(i => {
const r = {
...arr,
power:2
}
return r
})
console.log(newArr)
Now i get the wrong result, because one every iteration, the new array grow with a copy of the first array:
const r = {
...arr,
power:2
}
How to get the next result?
{
type:"Fiat", model:"500", color:"white", power: 2
},
{
type:"ford", model:"5300", color:"gray", power: 2
}

You are spreading arr .You need to spread i which is the object inside the array.
const arr = [
{
type:"Fiat", model:"500", color:"white"
},
{
type:"ford", model:"5300", color:"gray"
}
];
const newArr = arr.map(i => {
const r = {
...i,
power:2
}
return r;
})
console.log(newArr)
With array function you can implicitly
const arr = [
{
type:"Fiat", model:"500", color:"white"
},
{
type:"ford", model:"5300", color:"gray"
}
];
const newArr = arr.map(i => ({...i, power: 2}));
console.log(newArr)

You need to spread the current object that you are getting as:
const newArr = arr.map(i => ({ ...i, power: 2 }));

You want to do this, you are spreading arr and should be spreading the array getting passed to map (e.g. i):
const newArr = arr.map(i => {
const r = {
...i,
power:2
}
return r
})

Related

Object.keys(data).map(v) not giving the actual key value

I want to convert an object into an array of object but my code give the wrong result like shown below..
// object
data = { user_id : '123' }
// expected result
data = [ { user_id : '123' } ]
// what I get instead
data = [ { v : '123' } ]
my code:
let arr = [];
Object.keys(data).map(v => {
console.log(v, data[v]); // here it shows 'user_id' and '123' as it's supposed to
arr.push({ v:data[v] }); // but here it uses the 'v' as property instead of 'user_id'
});
You need to put v inside a square bracket
const data = {
user_id: '123'
}
let arr = [];
Object.keys(data).map(v => {
arr.push({
[v]: data[v]
});
});
console.log(arr)
Alternatively you can also use Object.entries. You dont need initialize let arr = []; as map will create a new array
const data = {
user_id: '123'
}
const arr = Object.entries(data).map(v => {
return {
[v[0]]: v[1]
}
});
console.log(arr)
when you need to use variable as key in object, you must use [].
Example:
const key = 'user_id'
const obj = {
[key]: 'user'
}
## result
{
'user_id': 'user
}
So change v to [v].
let arr = [];
Object.keys(data).map(v => {
arr.push({ [v]:data[v] }); // replace v to [v]
});

Extracting values out of an array of objects?

I am trying to extract id from the below array of objects and so far I am able to give it a go with the below code but it is showing undefined and cannot get id , would you please check the code and adjust to get id out?
const array = [{
contact: {
id: 1,
email: 'roar#gmail.com',
},
date: '2/4/22'
},
{
contact: {
id: 2,
email: 'grr#gmail.com',
},
date: '2/4/22'
}
]
function extractValue(arr, prop) {
let extractedValue = [];
for (let i = 0; i < arr.length; ++i) {
// extract value from property
extractedValue.push(arr[i][prop]);
}
return extractedValue;
}
const result = extractValue(array, 'contact.id');
console.log(result);
A good way to do this is the Array Map method
This will get all the id's from your array
const result = array.map((val) => val.contact.id)
const extractValue = (array, path) => {
const [first, second] = path.split('.')
if (second) return array.map(obj => obj[first][second])
return array.map(obj => obj[first])
}
const res = extractValue(array, 'contact.id')
console.log(res)
// => [ 1, 2 ]
this will support single and double level nested results
function find(val, arr) {
for (let x of arr)
val = val[x];
return val;
}
function extractValue(arr, prop) {
return array.map(x => find(x, prop.split(".")))
}

Mapping array of strings into array of specific object

I have a problem to make an array of strings into objects of url paths (for breadcrumbs)
I have this array :
const array = ['visit', 'schedule', 'validator']
What I tried :
const routeArray = array.map((b) => ({
label: b,
route: `/${b}`,
}))
console.log(routeArray)
result :
[
{label: "visit", route: "/visit"},
{label: "schedule", route: "/schedule"},
{label: "validator", route: "/validator"},
]
what I want to achieve :
[
{label: "visit", route: "/visit"},
{label: "schedule", route: "/visit/schedule"},
{label: "validator", route: "/visit/schedule/validator"}
]
Any help ?
Just concatenate the String while going through the array:
const array = ['visit', 'schedule', 'validator'];
let route = "";
const result = array.map(label => {
route += '/' + label;
return { label, route };
});
Array.prototype.map(), Array.prototype.slice() and Array.prototype.join() can be your best friends, here:
const input = ['visit', 'schedule', 'validator'];
const output = input.map((item, index) => {
return {
label: item,
route: '/' + input.slice(0, index + 1).join('/')
}
});
// test
console.log(output);
Please check this out and let me know if this is what you were looking for:
const array = ['visit', 'schedule', 'validator']
const newArray = array.map((entry, index) => {
const route = [];
for (let i = 0; i < index + 1; i++) {
route.push(array[i]);
}
return {
label: entry,
route: route.join('/'),
};
});
console.log(newArray);
In this approach, I loop through as many elements as the order of the current element of array, pushing them into the route array. When creating the object properties, I join the elements of route separated by '/'.
Here is how we can do this using the reduce method:
const arr = ["visit", "schedule", "validator"];
const res = arr.reduce((acc, curr, idx, self) => {
// Our route property of our needed data structure
const route = `/${self.slice(0, idx)}${idx > 0 ? "/" + curr : curr}`;
// Our new object
const obj = { label: curr, route };
return [...acc, obj];
}, []);
console.log(res);
Can be done using a for loop. You need to have a variable which tracks your incrementing route and persists over loop iterations.
const array = ['visit', 'schedule', 'validator'];
let ansArray = [];
let incrVal = '';
for(let i = 0 ; i < array.length; i++){
let ans = incrVal + '/' + array[i];
ansArray.push({'label' : array[i], 'route' : ans});
incrVal = ans;
}
console.log(ansArray);
const array = ['visit', 'schedule', 'validator'];
const results = array.map((item, index, arr) => {
return {
label: item,
route: '/' + arr.slice(0, index + 1).join('/'),
};
});
console.log(results);
Using reduce array method
const array = ["visit", "schedule", "validator"];
const res = array.reduce((acc, curr, idx, arr) => {
acc.push({
label: curr,
route:'/'+ arr.slice(0, idx + 1).join('/')
})
return acc;
}, []);
console.log(res);
I think this is the shortest way to do this:
const input = ["visit", "schedule", "validator"];
const res = input.map((label, i, arr) => ({
label,
route: '/' + arr.slice(0, i + 1).join("/")
}));
console.log(input);
console.log(res);

How to .push() each worker's result into an array in node js?

I crushed onto a wall pretty violently. The thing is that I am calling a function in the main thread with the form:
const {StaticPool} = require("node-worker-threads-pool");
const friendsTableWorkers = (result) => {
const pool = new StaticPool({
size: 8,
task: "./worker.js",
workerData: result
})
const nums = [23, 25]
let buffer = []
const size = Int32Array.BYTES_PER_ELEMENT*nums.length
const sharedBuffer = new SharedArrayBuffer(size)
const sharedArray = new Int32Array(sharedBuffer)
nums.forEach((num, index) => {
Atomics.store(sharedArray, index, num);
})
pool.exec(sharedArray).then(res => {
buffer.push( res )
}).finally(()=>{
console.log( buffer )
})
return buffer
}
which, in turn, use a fixed pool of workers of the form:
const { parentPort, workerData } = require("worker_threads")
const _ = require('lodash')
const { idToEnsembl } = require('./supportFunctionsBackend.js')
function friendSeeker(n) {
console.log(n)
let res = workerData.map(x => x._doc)
return {
ensemblGeneId: idToEnsembl(n),
nodeidentifier: n,
geneSetFriends: _.countBy(res, (o) => {
return (o.nodes.includes(n))
}).true}
}
parentPort.on("message", (param) => {
param.forEach( friend => {
if (typeof friend !== "number") {
throw new Error("param must be a number.");
}
const result = friendSeeker(friend);
parentPort.postMessage(result);
})
})
But, when I run it, I get the following:
23
[
{
ensemblGeneId: 'ENSG00000000003',
nodeidentifier: 23,
geneSetFriends: 2249
}
]
25
When the real result should be:
[
{
ensemblGeneId: 'ENSG00000000003',
nodeidentifier: 23,
geneSetFriends: 2249
},
{
ensemblGeneId: 'ENSG00000000005',
nodeidentifier: 25,
geneSetFriends: 321
}
]
or
[
{
ensemblGeneId: 'ENSG00000000005',
nodeidentifier: 25,
geneSetFriends: 321
},
{
ensemblGeneId: 'ENSG00000000003',
nodeidentifier: 23,
geneSetFriends: 2249
}
]
Which means that just one worker is pushing his result into the buffer array. My question is, then, how can I make all the workers push their result into the buffer array? The order is not important.
Thank you very much in advance

add elements to object - javascript

I'm trying to build an object given an array of objects
const someArray = [
{
name: 'x.y',
value: 'Something for Y'
},
{
name: 'x.a.z',
value: 'Something for Z'
}
]
to look like this
{
x: {
a: {
z: 'Something for Z'
},
y: 'Something for Y'
}
}
I have this code
const buildObj = data => {
let obj = {}
data.forEach(item => {
let items = item.name.split('.')
items.reduce((acc, val, idx) => {
acc[val] = (idx === items.length - 1) ? item.value : {}
return acc[val]
}, obj)
})
return obj
}
buildObj(someArray)
but it doesn't include the y keypair. what's missing?
What you want to do is create an object, then for each dotted path, navigate through the object, creating new object properties as you go for missing parts, then assign the value to the inner-most property.
const someArray = [{"name":"x.y","value":"Something for Y"},{"name":"x.a.z","value":"Something for Z"}]
const t1 = performance.now()
const obj = someArray.reduce((o, { name, value }) => {
// create a path array
const path = name.split(".")
// extract the inner-most object property name
const prop = path.pop()
// find or create the inner-most object
const inner = path.reduce((i, segment) => {
// if the segment property doesn't exist or is not an object,
// create it
if (typeof i[segment] !== "object") {
i[segment] = {}
}
return i[segment]
}, o)
// assign the value
inner[prop] = value
return o
}, {})
const t2 = performance.now()
console.info(obj)
console.log(`Operation took ${t2 - t1}ms`)
.as-console-wrapper { max-height: 100% !important; }
This is ABD at this point but I did it with a recursive builder of the path.
const someArray = [
{
name: 'x.y',
value: 'Something for Y'
},
{
name: 'x.a.z',
value: 'Something for Z'
}
]
const createPath = (path, value) => {
if(path.length === 1){
let obj = {}
obj[path.shift()] = value
return obj
}
let key = path.shift();
let outObject = {}
outObject[key] = { ...createPath(path, value) }
return outObject
}
const createObjectBasedOnDotNotation = (arr) => {
let outObject = {}
for(let objKey in arr){
const { name, value } = arr[objKey];
let object = createPath(name.split("."), value)
let mainKey = Object.keys(object)[0];
!outObject[mainKey] ?
outObject[mainKey] = {...object[mainKey]} :
outObject[mainKey] = {
...outObject[mainKey],
...object[mainKey]
}
}
return outObject
}
console.log(createObjectBasedOnDotNotation(someArray))
Here's an option using for loops and checking nesting from the top down.
const someArray = [
{
name: 'x.y',
value: 'Something for Y'
},
{
name: 'x.a.z',
value: 'Something for Z'
}
]
function parseArr(arr) {
const output = {};
for (let i = 0; i < arr.length; i++) {
const {name, value} = arr[i];
const keys = name.split('.');
let parent = output;
for (let j = 0; j < keys.length; j++) {
const key = keys[j];
if (!parent.hasOwnProperty(key)) {
parent[key] = j === keys.length - 1 ? value : {};
}
parent = parent[key];
}
}
return output;
}
console.log(parseArr(someArray));

Categories