I have static array constant of objects something similar to below.
export const EMPLOYEES = [
{
id: 2,
name: ‘John’,
},
{
id: 3,
name: ‘Doe’,
},
{
id: 4,
name: ‘Bull’,
},
{
id: 5,
name: ‘Scott’,
},
];
Now I need to add the last element only based on if some condition is true. Some this like if isAmerican() is true.
Can somebody help me here how to add element based on the condition? Thanks.
You can do it using spread operator:
export const EMPLOYEES = [
{
id: 2,
name: "John",
},
{
id: 3,
name: "Doe",
},
{
id: 4,
name: "Bull",
},
{
id: 5,
name: "Scott",
},
... isAmerican() ? [{ id: 6, name: "Jemmy"}] : []
];
You should never modify (or try to modify) a constant. I can see two ways you can do this:
Create a pure function to return a new constant with the new object added to the array
Use a spread operator in the definition of the constant
Option 1: Pure function
function makeNewArray(array, objectToAppend, isAmerican) {
return isAmerican ? [...array, objectToAppend] : array
}
const EMPLOYEES = [
{
id: 2,
name: "John",
},
{
id: 3,
name: "Doe",
},
{
id: 4,
name: "Bull",
},
{
id: 5,
name: "Scott",
}
];
const arrayWithAmerican = makeNewArray(EMPLOYEES, { id: 6, name: "American Frank"}, true);
const arrayWithoutAmerican = makeNewArray(EMPLOYEES, { id: 6, name: "Not American Frank"}, false);
console.log(arrayWithAmerican);
console.log(arrayWithoutAmerican);
Option 2: Spread operator
function isAmerican(){
// generic code here.
return true;
}
const EMPLOYEES = [
{
id: 2,
name: "John",
},
{
id: 3,
name: "Doe",
},
{
id: 4,
name: "Bull",
},
{
id: 5,
name: "Scott",
},
... isAmerican() ? [{ id: 6, name: "American Frank"}] : []
];
If the condition will be fulfilled, simply push an object to your EMPLOYEES array:
let isAmerican = true;
const EMPLOYEES = [
{
id: 2,
name: "John",
},
{
id: 3,
name: "Doe",
},
{
id: 4,
name: "Bull",
},
{
id: 5,
name: "Scott",
},
];
if(isAmerican) {
EMPLOYEES.push({
id: 6,
name: "Frank"
})
}
console.log(EMPLOYEES)
Fiddle: https://jsfiddle.net/rqx35pLz/
Related
My nested json array looks like:
[
{
id: 1,
name: "Mike",
children: [
{ id: 2, name: "MikeC1" },
{ id: 3, name: "MikeC2" },
{
id: 4, name: "MikeC3",
children: [{ id: 5, name: "MikeCC1" }]
},
]
},
{
id: 6,
name: "Json",
children: [
{ id: 7, name: "JsonC1" },
{ id: 8, name: "JsonC2" },
{
id: 9, name: "JsonC3",
children: [{ id: 10, name: "JsonCC1" },{ id: 11, name: "JsonCC2" }]
},
]
}
]
Now I get a id like "11"
then get the parent ids array in json like [6,9,11]
How to do?
var id = 11
console.log(findParent(id))
//result is [6,9,11]
You need to do recursive search
const persons = [
{
id: 1,
name: "Mike",
children: [
{ id: 2, name: "MikeC1" },
{ id: 3, name: "MikeC2" },
{
id: 4, name: "MikeC3",
children: [{ id: 5, name: "MikeCC1" }]
},
]
},
{
id: 6,
name: "Json",
children: [
{ id: 7, name: "JsonC1" },
{ id: 8, name: "JsonC2" },
{
id: 9, name: "JsonC3",
children: [{ id: 10, name: "JsonCC1" },{ id: 11, name: "JsonCC2" }]
},
]
}
];
function searchRecursive(items, id) {
const allIds = [];
items.forEach(item => {
if(item.id === id) {
allIds.push(item.id);
}
else if(item.children) {
const ids = searchRecursive(item.children, id);
if(ids.length) allIds.push(item.id);
ids.forEach(id => allIds.push(id));
}
});
return allIds;
}
console.log(searchRecursive(persons, 11));
I am trying to change the value of single key in an associative array which is inside another assoc array using javascript.
I have an array like this:
let arr = [{
id: 4,
name: 'test',
docs: [{
id: 1,
name: 'abc'
},{
id: 2,
name: 'xyz'
}]
}, {
id: 8,
name: 'test2',
docs: [{
id: 5,
name: 'abc'
},{
id: 7,
name: 'xyz'
}]
}]
I want to change the value of name of xyz to xyz (test), where test is name key of parent object and get final array as Output:
[{
id: 1,
name: 'abc (test)'
},
{
id: 2,
name: 'xyz (test)'
},
{
id: 5,
name: 'abc (test2)'
},
{
id: 7,
name: 'xyz (test2)'
}]
I am using approach.
let docs = new Array();
arr.forEach((item, index) => {
let docx = item.documents.map(item1 => {
item1.name = item1.name + " ("+item.name+")";
});
docs.push(docx);
});
return docs;
this is returning array of undefined array.
Try a flatMap
let arr = [{ id: 4, name: 'test', docs: [{ id: 1, name: 'abc' },{ id: 2, name: 'xyz' }] }, { id: 8, name: 'test2', docs: [{ id: 5, name: 'abc' },{ id: 7, name: 'xyz' }] }]
const output = arr.flatMap(item =>
item.docs.map(({id,name}) => ({ id, name: `${name} (${item.name})` }))
)
console.log(output)
There is an issue in your data, the docs inner array contains an object with duplicate keys:
let arr = [{
id: 4,
name: 'test',
docs: [{
id: 1,
name: 'abc',
id: 2, // <-- duplicate key
name: 'xyz' // <-- duplicate key
}]
},
If I remove the duplication, you can use this code to create a new object with the name value updated to xyz123 if the original value was xyz:
const original = [{
id: 4,
name: 'test',
docs: [{
id: 1,
name: 'abc'
}, {
id: 2,
name: 'xyz'
}]
}, {
id: 8,
name: 'test2',
docs: [{
id: 1,
name: 'abc'
}, {
id: 2,
name: 'xyz'
}]
}];
const updates = original.map(currentObject => {
const newObject = Object.assign(currentObject);
const newDocs = newObject.docs.map(doc => {
const newDoc = Object.assign(doc);
if (newDoc.name === "xyz") {
newDoc.name = "xyz123";
}
return newDoc;
});
newObject.docs = newDocs;
return newObject
});
console.log(updates);
How do I flatten the nested Array in the Array?
Here is the example input Array,
const input = [
{
id: 1,
name: 'Charles',
otherFields: [{
id: 2,
name: 'Pung',
}, {
id: 3,
name: 'James',
}]
}, {
id: 4,
name: 'Charles',
otherFields: [{
id: 5,
name: 'Pung',
}, {
id: 6,
name: 'James',
}]
}
]
Output Array I want to get.
[{
id: 1,
name: 'Charles'
}, {
id: 2,
name: 'Pung',
}, {
id: 3,
name: 'James',
}, {
id: 4,
name: 'Charles'
}, {
id: 5,
name: 'Pung',
}, {
id: 6,
name: 'James',
}]
I want to somehow get the output in one statement like
input.map((sth) => ({...sth??, sth.field...})); // I'm not sure :(
With flatMap you can take out the otherFields property, and returning an array containing the parent item and the other array:
const input = [{
id: 1,
name: 'Charles',
otherFields: [{
id: 2,
name: 'Pung',
}, {
id: 3,
name: 'James',
}]
}];
console.log(
input.flatMap(({ otherFields, ...item }) => [item, ...otherFields])
);
For more than one level, you could take a recursive approach of flattening.
const
flat = ({ otherFields = [], ...o }) => [o, ...otherFields.flatMap(flat)],
input = [{ id: 1, name: 'Charles', otherFields: [{ id: 2, name: 'Pung' }, { id: 3, name: 'James', otherFields: [{ id: 4, name: 'Jane' }] }] }],
result = input.flatMap(flat);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I have object and an array:
const response = [
{ id: 1, product: 'EL' },
{ id: 2, product: 'AC' },
{ id: 3, product: 'AC' },
{ id: 4, product: 'AD' },
{ id: 5, product: 'DE' },
];
const elProd = [
"EL"
"DE"
];
i want to filter out the product which has product code in elProd array.
my expectation is below:
const response = [
{ id: 2, product: 'AC' },
{ id: 3, product: 'AC' },
{ id: 4, product: 'AD' },
];
what I tried :
response.filter(obj => {return obj.product == elProd .includes(obj.product)})
const response = [{
id: 1,
product: 'EL'
},
{
id: 2,
product: 'AC'
},
{
id: 3,
product: 'AC'
},
{
id: 4,
product: 'AD'
},
{
id: 5,
product: 'DE'
},
];
const elProd = [
"EL",
"DE"
];
const filteredresp = response.filter((resp) => elProd.indexOf(resp.product) !== -1);
console.log(filteredresp);
response.filter(obj => {return !elProd.includes(obj.product)});
You almost got it, but you have a typo. You need a comma in the elProd array. Here's the code:
const response = [
{ id: 1, product: "EL" },
{ id: 2, product: "AC" },
{ id: 3, product: "AC" },
{ id: 4, product: "AD" },
{ id: 5, product: "DE" },
];
const elProd = [
"EL", // <-- Add the comma.
"DE",
];
// Don't forget to negate the includes here to exclude those you don't want.
const filtered = response.filter((obj) => !elProd.includes(obj.product));
// Result.
console.log(filtered);
You need only the check with includes.
const
response = [{ id: 1, product: 'EL' }, { id: 2, product: 'AC' }, { id: 3, product: 'AC' }, { id: 4, product: 'AD' }, { id: 5, product: 'DE' }],
elProd = ["EL", "DE"],
result = response.filter(obj => !elProd.includes(obj.product));
console.log(result);
You could use filter and some
const response = [
{ id: 1, product: 'EL' },
{ id: 2, product: 'AC' },
{ id: 3, product: 'AC' },
{ id: 4, product: 'AD' },
{ id: 5, product: 'DE' },
];
const elProd = [
"EL",
"DE"
]
res=response.filter(o=>!elProd.some(p=>o.product==p))
console.log(res)
I have a JSON list of objects with an id, name and reference to parent id :
const myList = [
{
id: 1,
name: "name1",
parentId: null
},
{
id: 5,
name: "name5",
parentId: 32
},
{
id: 32,
name: "name32",
parentId: 48
},
{
id: 48,
name: "name48",
parentId: 1
}
]
I would like to sort that list hierarchically, depending on the parent id :
[
{
id: 1,
name: "name1",
parentId: null
},
{
id: 48,
name: "name48",
parentId: 1
},
{
id: 32,
name: "name32",
parentId: 48
},
{
id: 5,
name: "name5",
parentId: 32
}
]
I'm new in Javascript programming and lodash, and I was wondering if there is an easy way to sort that list with lodash ?
Thank you in advance.
Benj
I found a solution with lodash.
Not sure it's the best but it works.
var parentId = null;
var sortedList = [];
var byParentsIdsList = _.groupBy(myList, "parentId"); // Create a new array with objects indexed by parentId
while (byParentsIdsList[parentId]) {
sortedList.push(byParentsIdsList[parentId][0]);
parentId = byParentsIdsList[parentId][0].id;
}
You can use lodash's method sortBy
var sorted = _.sortBy(myList, "parentId");
console.log(sorted);
/* OUTPUT
[
{
id: 1,
name: "name1",
parentId: null
},
{
id: 48,
name: "name48",
parentId: 1
},
{
id: 5,
name: "name5",
parentId: 32
},
{
id: 32,
name: "name32",
parentId: 48
}
]
*/
https://jsfiddle.net/L88t09ne/
with vanilla js [].sort() method:
const myList = [
{
id: 1,
name: "name1",
parentId: null
},
{
id: 5,
name: "name5",
parentId: 32
},
{
id: 32,
name: "name32",
parentId: 48
},
{
id: 48,
name: "name48",
parentId: 1
}
];
var arr = myList.sort(function(a,b){
return a.parentId -b.parentId
});
console.log(arr)