How can I merge two array values in java script [duplicate] - javascript

This question already has answers here:
JavaScript: How to join / combine two arrays to concatenate into one array?
(3 answers)
Closed 2 years ago.
var array= [
{
"Name": "mohan",
"DESCRIPTION": "Vendor"
},
{
"Name": "mahesh",
"DESCRIPTION": "Vendor1"
},
{
"Name": "manoj",
"DESCRIPTION": "Vendor2"
}]
var array2= [
{
"Name": "mohanraj",
"DESCRIPTION": "Vendor1"
},
{
"Name": "manojkumar",
"DESCRIPTION": "Vendor2"
},
{
"Name": "mohankumar",
"DESCRIPTION": "Vendor3"
}];
expected output
array3=[
{
"Name": "mohan",
"DESCRIPTION": "Vendor"
},
{
"Name": "mahesh",
"DESCRIPTION": "Vendor1"
},
{
"Name": "manoj",
"DESCRIPTION": "Vendor2"
},
{
"Name": "mohanraj",
"DESCRIPTION": "Vendor1"
},
{
"Name": "manojkumar",
"DESCRIPTION": "Vendor2"
},
{
"Name": "mohankumar",
"DESCRIPTION": "Vendor3"
}
];

You can do it like this
const arraymain = [
{
"Name": "mohan",
"DESCRIPTION": "Vendor"
},
{
"Name": "mahesh",
"DESCRIPTION": "Vendor1"
},
{
"Name": "manoj",
"DESCRIPTION": "Vendor2"
}]
const arraysecond = [
{
"Name": "mohanraj",
"DESCRIPTION": "Vendor1"
},
{
"Name": "manojkumar",
"DESCRIPTION": "Vendor2"
},
{
"Name": "mohankumar",
"DESCRIPTION": "Vendor3"
}];
const arraythird = array3=[
{
"Name": "mohan",
"DESCRIPTION": "Vendor"
},
{
"Name": "mahesh",
"DESCRIPTION": "Vendor1"
},
{
"Name": "manoj",
"DESCRIPTION": "Vendor2"
},
{
"Name": "mohanraj",
"DESCRIPTION": "Vendor1"
},
{
"Name": "manojkumar",
"DESCRIPTION": "Vendor2"
},
{
"Name": "mohankumar",
"DESCRIPTION": "Vendor3"
}
];
const arrayfinal = arraymain.concat(arraysecond,arraythird);
console.log(arrayfinal);

const array3 = array1.concat(array2):
See Array.prototype.concat

const array3 = [...array1, ...array2]
this will do shallow copy, which will avoid reference issues upto a level.

You can Array.prototype.concat method which allows to append value of one array to another Array
let first_array = [1,2,3,4];
let second_array = [5,6,7,8];
let results = first_array.concat(second_array);
console.log(results);
In you case you can perform that this way
let array3 = array.concat(array2):

I think that it very important to take your time learning the basics of Javascript.There ar 1000 ways to achieve this.
var array= [
{
"Name": "mohan",
"DESCRIPTION": "Vendor"
},
{
"Name": "mahesh",
"DESCRIPTION": "Vendor1"
},
{
"Name": "manoj",
"DESCRIPTION": "Vendor2"
}]
var array2= [
{
"Name": "mohanraj",
"DESCRIPTION": "Vendor1"
},
{
"Name": "manojkumar",
"DESCRIPTION": "Vendor2"
},
{
"Name": "mohankumar",
"DESCRIPTION": "Vendor3"
}];
//Without ES6
var arr3=array.concat(array2)
//With ES6 syntax
cons arr3=[...arr,...arr2]
For the rest learn the basics of Javascript...

The Array() constructor is used to create Array objects. You can create the third array by passing the elements of the first and second array elements as arguments. You could do that by using the spread operator.
let newArray = new Array(...firstArray, ...secondArray)

Related

Convert array of objects inside in object into array of properties

I have an Object which is having some properties like this:
obj1={
"id": 2,
"description": "",
"operationIds": [
{
"id": 1,
"name": "Standard"
}
],
"ratingIds": [
{
"id": 1,
"name": "name1",
"description": "",
},
{
"id": 4,
"name": "name4",
"description": "",
},
{
"id": 8,
"name": "name8",
"description": "",
},
],
}
I want covert the array of objects (operationIds and ratingIds) inside the object to array of properties, I'm receiving this object and I want to apply the change on it and supply another method so it should look like this:
obj1={
"id": 2,
"description": "",
"operationIds": [
1
],
"ratingIds": [
1,
4,
8
],
"timestamp": "AAAAAAAGJ6c=",
"estimatedUtilReconciliationApplies": true
}
I was able to do it but in a verry ugly way, is there a more simple and clear way to accomplish this ?
let x = {...obj} as any;
let ar1 = x.operationIds;
const arr1= ar1.map(function (obj) {
return obj.id;
});
let ar2 = x.ratingIds;
const arr2= ar2.map(function (obj) {
return obj.id;
});
x.operatingEnvironmentIds = arr1;
x.thrustRatingIds = arr2;
You can use spread operator and map
let obj1={
"id": 2,
"description": "",
"operationIds": [
{
"id": 1,
"name": "Standard"
}
],
"ratingIds": [
{
"id": 1,
"name": "name1",
"description": "",
},
{
"id": 4,
"name": "name4",
"description": "",
},
{
"id": 8,
"name": "name8",
"description": "",
},
],
}
console.log({
...obj1,
operationIds:obj1.operationIds.map(elem => elem.id),
ratingIds:obj1.ratingIds.map(elem => elem.id),
})
And as a function
let obj1={
"id": 2,
"description": "",
"operationIds": [
{
"id": 1,
"name": "Standard"
}
],
"ratingIds": [
{
"id": 1,
"name": "name1",
"description": "",
},
{
"id": 4,
"name": "name4",
"description": "",
},
{
"id": 8,
"name": "name8",
"description": "",
},
],
}
let transform = (obj) => {
return({
...obj,
operationIds:obj.operationIds.map(elem => elem.id),
ratingIds:obj.ratingIds.map(elem => elem.id),
})
}
let transformed = transform(obj1)
console.log(transformed)
We loop the array and use the Object.assign() method to convert an array of objects to a single object. This merges each object into a single resultant object.
The Object.assign() method also merges the properties of one or more objects into a single object.

How can I get the sites name data from JSON data

How can I get the sites name data value, with entire Formdata array?
Expected output:
["TEST-TRIAL-001120",
"Mubashir Test Site - 001001",
"TEST-TRIAL-001120",
"TEST SITE -001"]
const Formdata = [{
"id": "6efcf3f7-5d29-4a88-8ce9-346229a86765",
"title": "Deepak test form 2",
"version": "1",
"sites": [{
"id": "d7f2b290-2820-401a-a347-9a4dd05ec02b",
"name": "TEST-TRIAL-001120"
}],
"status": "Not Linked"
},
{
"id": "89e5a12d-913d-4f5d-a030-b172af9e27f0",
"title": "Deepak Test form 1",
"version": "1",
"sites": [],
"status": "Not Linked"
},
{
"id": "79a15768-762e-4ff8-b565-31274a38b22d",
"title": "1.7 Form",
"version": "1",
"sites": [{
"id": "32369d1d-f247-4a75-8c14-490c8393dbb8",
"name": "Mubashir Test Site - 001001"
}, {
"id": "d7f2b290-2820-401a-a347-9a4dd05ec02b",
"name": "TEST-TRIAL-001120"
}, {
"id": "a6526163-3ed7-4125-8f32-e0066fc6fe24",
"name": "TEST SITE -001"
}],
"status": "Not Linked"
}
]
Formdata.map(form => {
console.log(form.sites); //not understand how to get sites name data value
});
map over the site array to get an array of names, then flattening that array.
const Formdata=[{id:"6efcf3f7-5d29-4a88-8ce9-346229a86765",title:"Deepak test form 2",version:"1",sites:[{id:"d7f2b290-2820-401a-a347-9a4dd05ec02b",name:"TEST-TRIAL-001120"}],status:"Not Linked"},{id:"89e5a12d-913d-4f5d-a030-b172af9e27f0",title:"Deepak Test form 1",version:"1",sites:[],status:"Not Linked"},{id:"79a15768-762e-4ff8-b565-31274a38b22d",title:"1.7 Form",version:"1",sites:[{id:"32369d1d-f247-4a75-8c14-490c8393dbb8",name:"Mubashir Test Site - 001001"},{id:"d7f2b290-2820-401a-a347-9a4dd05ec02b",name:"TEST-TRIAL-001120"},{id:"a6526163-3ed7-4125-8f32-e0066fc6fe24",name:"TEST SITE -001"}],status:"Not Linked"}];
const result = Formdata.flatMap(({ sites }) => {
return sites.map(({ name }) => name);
});
console.log(result);
Additional documentation
Destructuring assignment
I use the flatMap and map
const Formdata = [{ "id": "6efcf3f7-5d29-4a88-8ce9-346229a86765", "title": "Deepak test form 2", "version": "1", "sites": [{ "id": "d7f2b290-2820-401a-a347-9a4dd05ec02b", "name": "TEST-TRIAL-001120" }], "status": "Not Linked" }, { "id": "89e5a12d-913d-4f5d-a030-b172af9e27f0", "title": "Deepak Test form 1", "version": "1", "sites": [], "status": "Not Linked" }, { "id": "79a15768-762e-4ff8-b565-31274a38b22d", "title": "1.7 Form", "version": "1", "sites": [{ "id": "32369d1d-f247-4a75-8c14-490c8393dbb8", "name": "Mubashir Test Site - 001001" }, { "id": "d7f2b290-2820-401a-a347-9a4dd05ec02b", "name": "TEST-TRIAL-001120" }, { "id": "a6526163-3ed7-4125-8f32-e0066fc6fe24", "name": "TEST SITE -001" }], "status": "Not Linked" } ];
const sites = Formdata.flatMap(({sites}) => sites.map(({name}) => name))
console.log(sites)
First map the sites names from each form. This leaves you with an array of arrays which you need to flatten, which can be done with concat or flatMap
const Formdata = [{"id": "6efcf3f7-5d29-4a88-8ce9-346229a86765","title": "Deepak test form 2","version": "1","sites": [{"id": "d7f2b290-2820-401a-a347-9a4dd05ec02b","name": "TEST-TRIAL-001120"}],"status": "Not Linked"},{"id": "89e5a12d-913d-4f5d-a030-b172af9e27f0","title": "Deepak Test form 1","version": "1","sites": [], "status": "Not Linked"},{"id": "79a15768-762e-4ff8-b565-31274a38b22d","title": "1.7 Form","version": "1","sites": [{"id": "32369d1d-f247-4a75-8c14-490c8393dbb8","name": "Mubashir Test Site - 001001"}, {"id": "d7f2b290-2820-401a-a347-9a4dd05ec02b","name": "TEST-TRIAL-001120"}, {"id": "a6526163-3ed7-4125-8f32-e0066fc6fe24","name": "TEST SITE -001"}],"status": "Not Linked"}]
let sites = [].concat.apply([],
Formdata.map(data =>
data.sites.map(site => site.name)
)
)
/*let sites = Formdata.map(data =>
data.sites.map(site => site.name)
).flatMap(x=>x)*/
console.log(sites)

Replacing a whole block of data in JSON file

I am looking for a way to replace a bunch of data in a JSON file without replacing another part of it:
{
"task": [
{
"id": 5,
"title": "dave",
"description": "test"
},
{
"id": 6,
"title": "fddsfsd",
"description": "fsdfsd"
},
{
"id": 7,
"title": "fddsfssdfsdfd",
"description": "fsdfsd"
},
{
"id": 8,
"title": "fddsfssdfsdfd",
"description": "fsdfsd"
}
],
"compteur": [
{
"id": 8
}
]
}
I manage to get everything that is in between the brackets of "task" in a variable.
My current issue is that I need to replace only what's inside the bracket and not affect the other parts of the file.
This is my code for retrieving the data of "tasks":
function RemoveNode(idToDelete) {
return jsonData.task.filter(function(emp) {
if (emp.id == idToDelete) {
return false;
}
return true;
});
}
var newData = RemoveNode(idToDelete);
arr1 = JSON.stringify(newData, null, 4);
console.log("arr1", arr1);
The console.log gives me:
arr1 [
{
"id": 5,
"title": "dave",
"description": "test"
},
{
"id": 6,
"title": "fddsfsd",
"description": "fsdfsd"
},
{
"id": 8,
"title": "fddsfssdfsdfd",
"description": "fsdfsd"
}
]
I actually need to replace this in the original JSON File but I have absolutely no idea how to achieve this.
You can use the spread operator, this will override the task data with your new filtered data
const removeNode = (idToDelete) =>
jsonData.task.filter((emp) => emp.id != idToDelete);
const newData = RemoveNode(idToDelete);
const updatedJSONData = {...jsonData, task: newData};
If your JSON file is not too large, you could consider changing the task array in your JS object (once you've read or imported it into your program) and then re-writing the json file.
JSON file before the program runs:
{
"task": [
{
"id": 5,
"title": "dave",
"description": "test"
},
{
"id": 6,
"title": "fddsfsd",
"description": "fsdfsd"
},
{
"id": 7,
"title": "fddsfssdfsdfd",
"description": "fsdfsd"
},
{
"id": 8,
"title": "fddsfssdfsdfd",
"description": "fsdfsd"
}
],
"compteur": [
{
"id": 8
}
]
}
Let's say we want to remove task objects with id=6. The code:
const myFileContents = require('./myFile.json');
const fs = require('fs');
const removeIdFromTasks = (taskList,idToRemove) => {
return taskList.filter(task => task.id!=idToRemove);
}
const writeJsonFile = (fileName,content) => {
fs.writeFile(fileName,content,(err) => {
if(err){
console.error(`Error in writing json file: ${e.message}`);
} else {
console.log(`File written`);
}
})
}
myFileContents.task = removeIdFromTasks(myFileContents.task,6);
writeJsonFile(`myFile.json`,JSON.stringify(myFileContents));
The same file after execution:
{
"task": [
{
"id": 5,
"title": "dave",
"description": "test"
},
{
"id": 7,
"title": "fddsfssdfsdfd",
"description": "fsdfsd"
},
{
"id": 8,
"title": "fddsfssdfsdfd",
"description": "fsdfsd"
}],
"compteur": [
{
"id": 8
}]
}

Javascript - grab value inside of an object nested within an object

I am trying to grab a value of a key inside of an object in an array which itself is an object in an array.
Here is what it looks like:
var books = [
{
"title": "title1",
"author": "author1",
"users": [
{
"id": 1,
"name": "Isidro"
},
{
"id": 4,
"name": "Jose Miguel"
},
{
"id": 3,
"name": "Trinidad"
}
]
},
{
"title": "title2",
"author": "author2",
"users": [
{
"id": 4,
"name": "Jose Miguel"
},
{
"id": 5,
"name": "Beatriz"
},
{
"id": 6,
"name": "Rosario"
}
]
},
What I am trying to do, 2 things:
First:
when I click on a user name in the HTML, I want to match the name clicked with the same user name in all the objects it is present in.
Second:
display the title of the books this user name is present in.
For example: when I click on Jose Miguel I want to see the 2 books he has read.
At the moment I have this:
var btnUser = document.querySelectorAll(".individualUsers");
for (var i = 0; i < btnUser.length; i++) {
btnUser[i].addEventListener("click", function() {
var clickedUser = this.innerText
var userBooks = books
.filter(x => x.users.name.indexOf(clickedUser) > -1)
.map(x => ` <li>${x.title}</li> <li>${x.author}</li>`);
console.log(clickedUser);
});
}
My problem is x.users.name.indexOf(clickedUser)is not accessing the user name.
You need to search inside the users array as well, one neat way is to do so with Array.some that return true if some of the conditional is true.
const books = [{
"title": "title1",
"author": "author1",
"users": [{
"id": 1,
"name": "Isidro"
},
{
"id": 4,
"name": "Jose Miguel"
},
{
"id": 3,
"name": "Trinidad"
}
]
},
{
"title": "title2",
"author": "author2",
"users": [{
"id": 4,
"name": "Jose Miguel"
},
{
"id": 5,
"name": "Beatriz"
},
{
"id": 6,
"name": "Rosario"
}
]
}
];
const clickedUser = 'Jose Miguel';
var userBooks = books
.filter(x => x.users.some(user => user.name.indexOf(clickedUser) > -1));
console.log(userBooks);

Convert a model in given json format

I have a model in which values are stored in following format:--
Language-count=3
[0]
-ID="1"
-Name="French"
[1]
-ID="2"
-Name="English"
[2]
-ID="3"
-Name="Hindi"
Titles-count=2
[0]
-ID="1"
-Name="Video1"
[1]
-ID="2"
-Name="Video2"
Countries-count=2
[0]
-ID="1"
-Name="India"
[1]
-ID="2"
-Name="USA"
and I have to convert this model in given json format:-
var models = [
{
name: 'Language',
values: [
'English',
'French',
'Hindi'
]
},
{
name: 'Title',
values: [
'Title 1',
'Title 2'
]
},
{
name: 'Countries',
values: [
'India',
'UK'
]
}
];
In above json format I have hard coded those values of Languages,countries and Titles but I have to fetch it from the above model which I have already given.
The json Format which I am getting is following:--
{
"ID": 1,
"DealID": 1,
"Title": "Position1",
"Titles": [
{
"Icon": "hdtv",
"Name": "\nWedding Bells & Farewells\n",
"ID": 12
},
{
"Icon": "hdtv",
"Name": "Delta Farce",
"ID": 5
},
{
"Icon": "hdtv",
"Name": "Doe B: Let Me Find",
"ID": 9
}
],
"Episodes": [
{
"Icon": "episode",
"Name": "Sparkle",
"ID": 4
},
{
"Icon": "episode",
"Name": "Sparks Fly Out",
"ID": 2
},
{
"Icon": "episode",
"Name": "Uploads by Filmi Gaane",
"ID": 7
}
],
"Assets": [
{
"Icon": "file-o",
"Name": "Best of Javed Akhtar - Jukebox 2 - Javed Akhtar Top 10 Hit Songs",
"ID": 10
},
{
"Icon": "file-o",
"Name": "Ep 105 - Sin Say Shun Awards After Party additional image 1",
"ID": 4
},
{
"Icon": "file-o",
"Name": "Ep 105 - Sin Say Shun Awards After Party box cover",
"ID": 3
}
],
"Documents": [],
"Languages": [
{
"Icon": "globe",
"Name": "Albanian",
"ID": 70
},
{
"Icon": "globe",
"Name": "Amharic",
"ID": 96
}
],
"Territories": [],
"Countries": [
{
"Icon": "globe",
"Name": "Afghanistan",
"ID": 2
},
{
"Icon": "globe",
"Name": "Albania",
"ID": 3
},
{
"Icon": "globe",
"Name": "Algeria",
"ID": 4
}
],
"Rights": [
{
"Icon": "leaf",
"Name": "Ancillary",
"ID": 23
},
{
"Icon": "leaf",
"Name": "Finshed Episode Rights",
"ID": 20
},
{
"Icon": "leaf",
"Name": "Format Group - DO NOT USE",
"ID": 63
}
],
"Contributors": [],
"Transmissions": [],
"Available": null
}
It would be best to write a simple parser and transform your data type to JSON - which would additionally allow you to reuse the parser in the future, and convert it to other data types easily for instance.
You could look at the various YAML parsers for inspiration, which would use a similiar technique for your data set's language.
Alternatively you can create a 'hack' and just keep splitting things up if your data format is always of this format, and doesn't allow arbitrary value nesting.
List personel = new List();
var client = new RestClient("your adres");
var request = new RestRequest(Method.GET);
request.AddHeader("Postman-Token", "2893de4a-457e-46a7e8efb025");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("token", "a23a80f7-3323-4594056");
IRestResponse response = client.Execute(request);
JObject deger = JObject.Parse(response.Content);
var toplam = deger["data"]["data"].Count();
string jenp = toplam.ToString();
for (int i = 0; i < toplam; i++)
{
Personeller data = new Personeller();
data.Adi = deger["data"]["data"][i]["adi"].ToString();
data.Soyadi = deger["data"]["data"][i]["soyadi"].ToString();
data.tckimlikno = (long)deger["data"]["data"][i]["tckimlikno"];
personel.Add(data);
}

Categories