How can I update object in an array in Nodejs? - javascript

This is my array
const arr = [
{ id: "1", hello: "hello1" },
{ id: "2", hello: "hello2" },
];
I want this code
const finalarr = [
{ id: "1", hello: "hello1", bye: 'bye1' },
{ id: "2", hello: "hello2", bye: 'bye2' },
];

Try with map:
var arr = [{ id: "1", hello: "hello1" },{ id: "2", hello: "hello2" }];
result = arr.map(elem=>({...elem, 'bye':`bye${elem.id}`})); // with attaching the id
result2 = arr.map((elem,i)=>({...elem, 'bye':`bye${i+1}`})); // by generating id;
console.log(result);
console.log(result2);

By using the below loop in your code you can get ur required output.
for (var i =0;i<arr.length;i++){
arr[i]["bye"] = "bye"+(i+1);
}

Related

How to convert array of object property?

I'm trying to convert array of objects having value as a array -> into string. I'm facing blocker in this,
let peopleDetails = [
{
name: "raj",
favCar: [{ name: "audi", color: "white" }],
favFood: [{ color: "brown", name: "Idli" }],
},
{ name: "deepak", place: "India", favPlace: [{ name: "Tajmahal" }] },
];
I need structure like,
let peopleDetails = [
{ name: "raj", favCar: "audi", favFood: "Idli" },
{ name: "deepak", place: "India", favPlace: "Tajmahal" },
];
For what I understand you want the value of every property to become the name value of its first element, when the value is an array of object.
Here's an immutable solution that follows this concept:
let peopleDetails = [
{
name: 'raj',
favCar: [{ name: 'audi', color: 'white' }],
favFood: [{ name: 'Idli' }],
},
{ name: 'deepak', place: 'India', favPlace: [{ name: 'Tajmahal' }] },
];
const result = peopleDetails.map(obj =>
Object.fromEntries(Object.entries(obj).map(([key, value]) =>
[key, value?.[0]?.name ?? value]
))
);
console.log(result);
I'm not sure why you've got arrays of singular elements (favourites typically don't have second or third places) so if you just want to extract the name from each item that's an array, take it from the first element in each array:
let peopleDetails = [{
name: "raj",
favCar: [{
name: "audi",
color: "white"
}],
favFood: [{
name: "Idli"
}],
},
{
name: "deepak",
place: "India",
favPlace: [{
name: "Tajmahal"
}]
},
];
let peopleDetailsModified = peopleDetails.map(o => {
let retObj = {};
for (key in o) {
if (Array.isArray(o[key])) {
retObj[key] = o[key][0].name;
} else {
retObj[key] = o[key];
}
}
return retObj;
});
console.log(peopleDetailsModified);
I've made this code more verbose than it needs to be, it's quite easy to one-line it using reduce.
I'm also quite not sure what you're trying to achieve as the other answers but I tried to make a map of the current object to an object that is more to your liking. I formatted it a little so you can see what I did:
peopleDetails.map(item => {
return {
name: item.name,
place: item.place,
favCar: item.favCar ? item.favCar[0].name : "",
favPlace: item.favPlace ? item.favPlace[0].name : "",
favFood: item.favFood ? item.favFood[0].name : ""}});
I have ran the code and its a generic code for similar data
const _ = require('lodash')
const peopleDetails =[
{
"name": "raj",
"favCar": [
{
"name": "audi",
"color": "white"
}
],
"favFood": [
{
"name": "Idli"
}
]
},
{
"name": "deepak",
"place": "India",
"favPlace": [
{
"name": "Tajmahal"
}
]
}
]
const newPeopleDetails = peopleDetails.map(obj => {
const formObj = {
favCar: obj && obj.favCar && obj.favCar[0].name,
favFood: obj && obj.favFood && obj.favFood[0].name,
favPlace: obj && obj.favPlace && obj.favPlace[0].name
}
const finalObj = _.pickBy(formObj, _.identity);
return Object.assign({}, obj, finalObj);
});
console.log(newPeopleDetails)

Creating an array from 2 other arrays

I have two arrays of objects as shown below :
categories = [
{ name: "performance", id: 1 },
{ name: "understanding", id: 2 }
]
queries = [
{ name: "A", categoryId: "1" },
{ name: "B", categoryId: "1" },
{ name: "C", categoryId: "1" },
{ name: "D", categoryId: "2" }
]
Now, using these two arrays of objects, I need following array as a result:
process = [
{ category: "performance", query: [
{ name: "A" },
{ name: "B" },
{ name: "C" }
]},
{ category: "understanding", query: [{ name: "D" }] }
]
I have to match the categoryId with process's id and then create the above array.
I have tried the following way to solve this but could not get desired result.
const test = [];
categories.forEach((element) => {
const r = que.filter((res) => res.categoryId === element.id);
queries.forEach((rt) => {
if (rt.categoryId === element.id) {
test.push({
category: element.name,
query: [{
name: rt.name,
}],
});
}
});
});
Is this possible using any built in array methods in JavaScript?
Thanks in advance
Using Array.reduce, you can group queries by categoryId.
Based on that groupedBy object, using Array.map, you can get the result you want.
const categories = [{
name: "performance",
id: "1"
},{
name: "understanding",
id: "2"
}];
const queries = [{
name: "A",
categoryId: "1"
}, {
name: "B",
categoryId: "1"
}, {
name: "C",
categoryId: "1"
}, {
name: "D",
categoryId: "2"
}];
const groupByQueries = queries.reduce((acc, cur) => {
acc[cur.categoryId] ?
acc[cur.categoryId].push({ name: cur.name })
: acc[cur.categoryId] = [ { name: cur.name } ];
return acc;
}, {});
const result = categories.map(({ name, id }) => ({
category: name,
query: groupByQueries[id]
}));
console.log(result);
categories = [{name: "performance", id: 1},{name: "understanding", id: 2}];
queries = [{name: "A", categoryId: "1"}, {name: "B", categoryId: "1"}, {name: "C", categoryId: "1"}, {name: "D", categoryId: "2"}]
const test = [];
categories.forEach((element) => {
let temp = []
queries.map(item =>{
if(element.id.toString() === item.categoryId)
temp.push({name: item.name})
})
test.push({category:element.name,query:temp})
});
console.log(test)

use filter of Lodash/Javascript to get the filtered data

I have two array of objects.
const firstObj = [
{ Id: "1", Name: "Peter" },
{ Id: "2", Name: "John" },
{ Id: "12", Name: "jessy" },
];
const secondObj = [
{ Id: "1", Name: "Roa", original: { Id: "1" } },
{ Id: "2", Name: "John2", original: { Id: "2" } },
{ Id: "5", Name: "Rachel", original: { Id: "3" } },
];
Here, I am trying to filter data on the basis of Id and return the filtered firstObj
So, here firstObj has an entry { Id: "12", Name: "jessy" } this object whose Id does not match with the secondObj.original.Id so, firstObj will have the given result.
what I tried was
firstObj.filter(
firstObj,
secondObj.map((second) => {
return firstObj.Id === second.original.Id;
}),
);
But this does not work. Can any one help me out here , using Lodash or Js filter.
output would be -> [{"Id": "3", "Name": "jessy"}]
Is this what you are looking for?
const firstObj = [
{ Id: "1", Name: "Peter" },
{ Id: "2", Name: "John" },
{ Id: "12", Name: "jessy" },
];
const secondObj = [
{ Id: "1", Name: "Roa", original: { Id: "1" } },
{ Id: "2", Name: "John2", original: { Id: "2" } },
{ Id: "1", Name: "Rachel", original: { Id: "3" } },
];
const result = lodash.filter(firstObj, (firstItem) => {
return !lodash.some(secondObj, (secondItem) => {
return firstItem.Id === secondItem.original.Id;
});
});
Live: https://stackblitz.com/edit/js-addy5t?file=index.js
why use loadash for this. you can use native filter and find functions to achieve this
const filter = firstObj.filter(item => {
return secondObj.find(itm => itm.original.id === item.id)
});
You could use native method of Array.filter() and Array.some() to achieve the desired output.
Please check below working code snippet
ES6
const firstObj = [
{ Id: "1", Name: "Peter" },
{ Id: "2", Name: "John" },
{ Id: "12", Name: "jessy" },
],
secondObj = [
{ Id: "1", Name: "Roa", original: { Id: "1" } },
{ Id: "2", Name: "John2", original: { Id: "2" } },
{ Id: "1", Name: "Rachel", original: { Id: "3" } },
];
let result = firstObj.filter(({Id})=> !secondObj.some(item => item.original.Id === Id));
console.log(result)

How to merge two arrays with new property in javascript

How to merge two arrays in javascript.I tried but not working. How to add new property like details and how to merge in single array
Demo: https://stackblitz.com/edit/js-6cfbaw
Example:
var array1 = [
{
id: 1,
name: "Zohn",
},
];
var array2 = [
{
name: "Zohn",
address: "Test1",
},
{
name: "Zohn Peter",
address: "Test2",
},
{
name: "Peter Mark",
address: "Test3",
},
];
var array3 = [...array1, ...array2];
Output array3 should be :
[
{
id: 1,
name: "Zohn",
details: [
{
name: "Zohn Zeo",
address: "Test1",
},
{
name: "Zohn Peter",
address: "Test2",
},
{
name: "Peter Mark",
address: "Test3",
},
],
},
];
No need to merge the arrays, you are just adding an attribute to the first element of array1.
var array1 = [
{
id:1,
name:"Zohn"
}
]
var array2 = [
{
name:"Zohn",
address:"Test1"
},
{
name:"Zohn Peter",
address:"Test2"
},
{
name:"Peter Mark",
address:"Test3"
}
]
array1[0]['details'] = array2
console.log(array1)
I hope this piece of code helps you.
var array1 =[];
var itemOfArray= {
id:1,
name:"Zohn" ,
details: [ ]
};
var array2 = [
{
name:"Zohn",
address:"Test1"
},
{
name:"Zohn Peter",
address:"Test2"
},
{
name:"Peter Mark",
address:"Test3"
}
]
itemOfArray['details']=array2;
array1.push(itemOfArray);
console.log(array1);
Try this example
var array1 = [
{
id: 1,
name: "Zohn",
},
];
var array2 = [
{
name: "Zohn",
address: "Test1",
},
{
name: "Zohn Peter",
address: "Test2",
},
{
name: "Peter Mark",
address: "Test3",
},
];
const output = array1.map((entry) => ({ ...entry, details: [...array2] }));
console.dir(output, { depth: null, color: true });
If you want to merge details, you have to keep a reference for each record of array1 in array2 and then merge as shown below.
var array1=[
{
id:1,
name:"Zohn"
}
];
var array2=[
{
array1Id: 1,
name:"Zohn",
address:"Test1"
},
{
array1Id: 1,
name:"Zohn Peter",
address:"Test2"
},
{
array1Id: 1,
name:"Peter Mark",
address:"Test3"
}
];
var array3 = [];
array1.forEach((entry) => {
array3.push(
{
id: entry.id,
name: entry.name,
details: array2.filter((value) => {
return value.array1Id == entry.id;
})
}
);
});
console.log(array3);

Removing object from array in array object

http://jsfiddle.net/0444046b/12/
I have a complex Array of objects, each object has it's own tag Array.
I also have just an object which should match one of the objects in the tag Array, and if so remove that tag.
Got some help here, however my example there was too simple, so far no luck with this below.
Basically I have the object tag and I need to remove it from the tags Array inside of tagsArray.
var tagsArray = [{
name: "group1",
tags: [
{
name: "1",
tag_id: "1234"
},
{
name: "2",
tag_id: "5678"
},
{
name: "3",
tag_id: "9012"
}
]
},
{
name: "group2",
tags: []
}
];
console.log(tagsArray[0]);
// Need to find this inside of tags inside of tagsArray and remove it:
var tag = {
name: "3",
tag_id: "9012"
}
var temp_array = [];
temp_array.push(tag);
var map = {};
tagsArray.forEach(function(obj, index) {
map[obj.tag_id] = index;
});
console.log(map);
temp_array.forEach(function(obj) {
if ( obj.tag_id ) {
tagsArray.splice(tagsArray[map[obj.tag_id]]);
console.log(tagsArray);
}
});
You can loop through each item in tagsArray and then filter our matching elements in the inner tags property.
var tagsArray = [{
name: "group1",
tags: [{
name: "1",
tag_id: "1234"
}, {
name: "2",
tag_id: "5678"
}, {
name: "3",
tag_id: "9012"
}]
}, {
name: "group2",
tags: []
}];
// Need to find this inside of tags inside of tagsArray and remove it:
var removeTag = {
name: "3",
tag_id: "9012"
}
var message = 'Before:<br>' + JSON.stringify(tagsArray) + '<br><br>';
tagsArray.forEach(function(element) {
element.tags = element.tags.filter(function(tag) {
return tag.name != removeTag.name && tag.tag_id != removeTag.tag_id;
})
});
message += 'After:<br>' + JSON.stringify(tagsArray);
document.body.innerHTML = message
The solution of Daniel Imms is totally fine, but this one also can solve your problem, and it is a bit faster.
var tagsArray = [{
name: "group1",
tags: [{
name: "1",
tag_id: "1234"
}, {
name: "2",
tag_id: "5678"
}, {
name: "3",
tag_id: "9012"
}]
}, {
name: "group2",
tags: [{
name: "4",
tag_id: "1012"
}]
}];
var removedTag = {
name: "4",
tag_id: "1012"
};
var message = 'Before:</br>' + JSON.stringify(tagsArray) + '</br></br>';
tagsArray.forEach(function(obj, i) {
obj.tags.forEach(function(tag, j) {
if (tag.tag_id === removedTag.tag_id && tag.name === removedTag.name) {
obj.tags.splice(j, 1);
return;
}
});
});
message += 'After:</br>' + JSON.stringify(tagsArray);
document.body.innerHTML = message
I tested with jsPerf and here is the link and here is the result.

Categories