Merge two json arrays - javascript

I have to array i want to merge them in one array by same id. So every two array have same id should be merged
Case 1:
{
"id":1212,
"instructor":"william",
...
}
Case 2:
[
{
"id":1212,
"name":"accounting",
...
},
{
"id":1212,
"name":"finance",
...
}
]
I need the result to be :
{
"id": 1212,
"instructor": "william",
"Courses": [
{
"id":1212,
"name":"accounting",
...
},
{
"id":1212,
"name":"finance",
...
}
]
}

What you're asking isn't merging, but here is how you can do that.
const instructors = [{ "id":1212, "instructor":"william", }];
const courses = [
{ "id":1212, "name":"accounting" },
{ "id":1212, "name":"finance" }
];
const expected = [{ "id":1212, "instructor":"william", "courses": [
{ "id":1212, "name":"accounting" },
{ "id":1212, "name":"finance" }
]}];
const composed = instructors.map(ins => {
const ret = {...ins};
ret.courses = courses.filter(cou => cou.id === ins.id);
return ret;
});
console.log(composed);

var finArr;
var course = [];
use forEach loop javascript get all value in put your value instead of varid and varname
course.push({"id":varid,"name":varname});
finArr = {"id":variableId,"instructor":variablename,"Courses":course}

Related

moving a key value pair out of an array

I am trying to move everything in the Array Results outside and into the original object
this is the object
{
"Name": "John",
"Results": [
{
"Type": "DB",
"Immediate_Action": "No",
}
]
}
It should look like this
{
"Name": "John",
"Type": "DB",
"Immediate_Action": "No",
}
What I have so far is this
const mapOscarResults = ({ data }) => {
return data.map(entry => {
let mapped = {...entry};
entry.Results.forEach(key => {
let Type = mapped[key.Type]
if (mapped[key]) {
mapped[key].push(entry.Results[key]);
} else {
mapped[key] = [entry.Results[key]];
}
});
return mapped;
});
};
You can simply spread the Results array into an Object.assign() call.
const input = { "Name": "John", "Results": [{ "Type": "DB", "Immediate_Action": "No", }, { "Another": "value" }] };
const { Results, ...refactored } = input;
Object.assign(refactored, ...Results);
console.log(refactored)
This code works for your example:
const { Results: results, ...rest } = {
"Name": "John",
"Results": [
{
"Type": "DB",
"Immediate_Action": "No",
}
]
}
const res = {...rest, ...results.reduce((prev, curr) => ({
...prev,
...curr
}), {})}
console.log(res)
But I don't know what you expect when the Results array has more than one element.
In that condition, if this code does not fill your needs, ask me to change it.
however, it will join first Result with index 0, you can expand it
const data = {
"Name": "John",
"Results": [
{
"Type": "DB",
"Immediate_Action": "No",
}
]
}
const mapOscarResults = (data) => {
for (let i in Object.keys(data)){
if (Array.isArray(data[Object.keys(data)[i]])){
newKey = data[Object.keys(data)[i]][0]
data = {... data, ...newKey}
delete data[Object.keys(data)[i]]
}
}
return data
};
console.log(mapOscarResults(data))

Trying to 'map' nested JSON element object (javascript)

I am trying to 'map' nested JSON elements that have objects in order to build HTML. I am not sure what I am doing wrong with the syntax as follows:
array1 = [
{
"name":"test",
"things": [
{ "name":"thing1" },
{ "name": "thing2"}
]
}
];
const createThingy = (item) => `
<p>${item.name}</p>
`
// pass a function to map
const map1 = array1.things.map(createThingy).join('');
console.log(array1);
// expected output: <p>thing1</p><p>thing2</p>
Thank you in advance for your time and consideration.
Think of the array as an object. It's accessed in a similar way, so if it were an object it would be like this:
let array1 = {
0: {
"name":"test",
"things": [
{ "name": "thing1" },
{ "name": "thing2" }
]
}
};
Therefore, to access its first element directly you need:
array1[0].things
To get your desired outcome you need to the following:
let array1 = [
{
"name": "test",
"things": [
{ "name": "thing1" },
{ "name": "thing2" }
]
}
];
const createThingy = (item) => `
<p>${item.name}</p>
`;
// pass a function to map
const map1 = array1[0].things.map(createThingy).join('');
console.log(map1);
In case your array can have multiple elements, you can use the following:
let array1 = [
{
"name": "test",
"things": [
{ "name": "thing1" },
{ "name": "thing2" }
]
}
];
const createThingy = (item) => `
<p>${item.name}</p>
`;
// pass a function to map
const map1 = array1.reduce((acc, elem) => acc + elem.things.map(createThingy).join(''), "");
console.log(map1);
array1 = [
{
"name":"test",
"things": [
{ "name":"thing1" },
{ "name": "thing2"}
]
}
];
const createThingy = (item) => `
<p>${item.name}</p>
`
// pass a function to map
const map1 = array1[0].things.map(createThingy).join('');
console.log(array1);
console.log(map1);
As Nick Parsons said, you have to loop over the array1 array to get things property.
const array1 = [
{
"name":"test",
"things": [
{ "name":"thing1" },
{ "name": "thing2"}
]
}
];
const createThingy = (item) => `
<p>${item.name}</p>
`
// pass a function to map
const map1 = array1[0].things.map(createThingy).join('');
console.log(array1);
console.log(map1);
Also, be advised that if your array1 variable is empty or in case there is no things attribute in preferred index, your code code will give error. Be sure to check if they are empty. You can do this by using lodash isEmpty function.
You have to loop over the array1 to get the desired output as Nick Parsons said in the comments.
array1 = [
{
"name":"test",
"things": [
{ "name":"thing1" },
{ "name": "thing2"}
]
}
];
const createThingy = (item) => `
<p>${item.name}</p>
`
array1.map(item => {
item.map(key => createThingy(key).join(''));
});
// expected output: <p>thing1</p><p>thing2</p>

Map Json data by JavaScript

I have a Json data that I want to have in a different format.
My original json data is:
{
"info": {
"file1": {
"book1": {
"lines": {
"102:0": [
"102:0"
],
"105:4": [
"106:4"
],
"106:4": [
"107:1",
"108:1"
]
}
}
}
}
}
And I want to map it as following:
{
"name": "main",
"children": [
{
"name": "file1",
"children": [
{
"name": "book1",
"group": "1",
"lines": [
"102",
"102"
],
[
"105",
"106"
],
[
"106",
"107",
"108"
]
}
],
"group": 1,
}
],
"group": 0
}
But the number of books and number of files will be more. Here in the lines the 1st part (before the :) inside the "" is taken ("106:4" becomes "106"). The number from the key goes 1st and then the number(s) from the value goes and make a list (["106", "107", "108"]). The group information is new and it depends on parent-child information. 1st parent is group 0 and so on. The first name ("main") is also user defined.
I tried the following code so far:
function build(data) {
return Object.entries(data).reduce((r, [key, value], idx) => {
//const obj = {}
const obj = {
name: 'main',
children: [],
group: 0,
lines: []
}
if (key !== 'reduced control flow') {
obj.name = key;
obj.children = build(value)
if(!(key.includes(":")))
obj.group = idx + 1;
} else {
if (!obj.lines) obj.lines = [];
Object.entries(value).forEach(([k, v]) => {
obj.lines.push([k, ...v].map(e => e.split(':').shift()))
})
}
r.push(obj)
return r;
}, [])
}
const result = build(data);
console.log(result);
The group information is not generating correctly. I am trying to figure out that how to get the correct group information. I would really appreciate if you can help me to figure it out.
You could use reduce method and create recursive function to build the nested structure.
const data = {"info":{"file1":{"book1":{"lines":{"102:0":["102:0"],"105:4":["106:4"],"106:4":["107:1","108:1"]}}}}}
function build(data) {
return Object.entries(data).reduce((r, [key, value]) => {
const obj = {}
if (key !== 'lines') {
obj.name = key;
obj.children = build(value)
} else {
if (!obj.lines) obj.lines = [];
Object.entries(value).forEach(([k, v]) => {
obj.lines.push([k, ...v].map(e => e.split(':').shift()))
})
}
r.push(obj)
return r;
}, [])
}
const result = build(data);
console.log(result);
I couldn't understand the logic behind group property, so you might need to add more info for that, but for the rest, you can try these 2 functions that recursively transform the object into what you are trying to get.
var a = {"info":{"file1":{"book1":{"lines":{"102:0":["102:0"],"105:4":["106:4"],"106:4":["107:1","108:1"]}}}}};
var transform = function (o) {
return Object.keys(o)
.map((k) => {
return {"name": k, "children": (k === "lines" ? parseLines(o[k]) : transform(o[k])) }
}
)
}
var parseLines = function (lines) {
return Object.keys(lines)
.map(v => [v.split(':')[0], ...(lines[v].map(l => l.split(":")[0]))])
}
console.log(JSON.stringify(transform(a)[0], null, 2));

Build array from another array if some key are identical using JavaScript

I have an array of data. Some of the key in the array are same. I would like to create a new array based on the key and add the other data.
This is my array
var myObjOne = [
{
"name":"John",
"id":1,
"car":"maruti"
},
{
"name":"John",
"id":2,
"car":"wolks"
},
{
"name":"John",
"id":3,
"car":"bmw"
},
{
"name":"Peter",
"id":4,
"car":"alto"
},
{
"name":"Peter",
"id":5,
"car":"swift"
}
];
I would like to convert the array in to the below format.
var myObj = [
{
"name":"John",
"items": [
{ "id":1, "car":"maruti" },
{ "id":2, "car":"wolks" },
{ "id":3, "car":"bmw" }
]},
{
"name":"Peter",
"items": [
{ "id":4, "car":"alto" },
{ "id":5, "car":"swift" },
]
}
];
I am working on a node environment.
You can create an object using Array#reduce first which maps name with items, and then create the final array by looping over the intermediate map using a for...of loop:
var source = [{"name":"John","id":1,"car":"maruti"},{"name":"John","id":2,"car":"wolks"},{"name":"John","id":3,"car":"bmw"},{"name":"Peter","id":4,"cars":"alto"},{"name":"Peter","id":5,"cars":"swift"}];
const map = source.reduce((acc, {name, ...obj}) => {
if (!acc[name]) {
acc[name] = [];
}
acc[name].push(obj);
return acc;
}, {});
const result = [];
for (let[name, items] of Object.entries(map)) {
result.push({name, items});
}
console.log(result);
Array.reduce is at rescue.This method accepts an accumulator and current
item. Check in the accumulator if there exist an object where the value of name property is John or Peter
var myObjOne = [{
"name": "John",
"id": 1,
"car": "maruti"
},
{
"name": "John",
"id": 2,
"car": "wolks"
},
{
"name": "John",
"id": 3,
"car": "bmw"
},
{
"name": "Peter",
"id": 4,
"car": "alto"
},
{
"name": "Peter",
"id": 5,
"car": "swift"
}
];
var newObj = myObjOne.reduce(function(acc, curr, currIndex) {
// using findIndex to check if there exist an object
// where the value of the name property is John, Peter
// if it exist it will return the index else it will return -1
let ifNameExist = acc.findIndex(function(item) {
return item.name === curr.name;
})
// if -1 then create a object with name and item property and push
// it to the accumulator
if (ifNameExist === -1) {
let nameObj = {};
nameObj.name = curr.name;
nameObj.items = [];
nameObj.items.push({
id: curr.id,
car: curr.car
})
acc.push(nameObj)
} else {
// if such an object already exist then just update the item array
acc[ifNameExist].items.push({
id: curr.id,
car: curr.car
})
}
return acc;
}, []);
console.log(newObj)
Use .reduce to group by name, and use .find inside the reducer to find if the matching name has already been added:
const input=[{"name":"John","id":1,"car":"maruti"},{"name":"John","id":2,"car":"wolks"},{"name":"John","id":3,"car":"bmw"},{"name":"Peter","id":4,"cars":"alto"},{"name":"Peter","id":5,"cars":"swift"}]
const output = input.reduce((a, { name, ...item }) => {
const foundNameObj = a.find(nameObj => nameObj.name === name);
if (foundNameObj) foundNameObj.items.push(item);
else a.push({ name, items: [item] });
return a;
}, []);
console.log(output);

How to insert objects through javascript?

I have stored group of objects into one array called 'resData' and i'm having one more array of data called 'approvedIds', there have included all approved id's. Here i want to match these two arrays and add one new key into 'resData' array like 'approveStatus:"approve"'. How to do this one in javascript?
All data's,
var resData = [
{
firstName:"Jhon",
lastName:"adam",
emailId:"jhn12#gmail.com",
id:"01"
},
{
firstName:"Kyle",
lastName:"Miller",
emailId:"kl12#gmail.com",
id:"02"
},
{
firstName:"Jhonathan",
lastName:"adam",
emailId:"jadm12#gmail.com",
id:"03"
},
{
firstName:"Lewis",
lastName:"harber",
emailId:"lewh12#gmail.com",
id:"04"
}
];
Approved id's array,
var approvedIds = ['01', '03'];
My output will be like this,
var resData = [
{
firstName:"Jhon",
lastName:"adam",
emailId:"jhn12#gmail.com",
id:"01",
approveStatus:'approved'
},
{
firstName:"Kyle",
lastName:"Miller",
emailId:"kl12#gmail.com",
id:"02"
},
{
firstName:"Jhonathan",
lastName:"adam",
emailId:"jadm12#gmail.com",
id:"03",
approveStatus:'approved'
},
{
firstName:"Lewis",
lastName:"harber",
emailId:"lewh12#gmail.com",
id:"04"
}
];
You can try this. Use forEach and indexOf functions
var resData = [
{
firstName:"Jhon",
lastName:"adam",
emailId:"jhn12#gmail.com",
id:"01"
},
{
firstName:"Kyle",
lastName:"Miller",
emailId:"kl12#gmail.com",
id:"02"
},
{
firstName:"Jhonathan",
lastName:"adam",
emailId:"jadm12#gmail.com",
id:"03"
},
{
firstName:"Lewis",
lastName:"harber",
emailId:"lewh12#gmail.com",
id:"04"
}
];
var approvedIds = ['01', '03'];
resData.forEach(item => {
if(approvedIds.indexOf(item.id) !== -1){
item.approvedStatus = 'approved';
}
} );
console.log(resData);
Using ES6 array functions, which is more functional and doesn't alter the original objects:
var resData = [
{
firstName:"Jhon",
lastName:"adam",
emailId:"jhn12#gmail.com",
id:"01"
},
{
firstName:"Kyle",
lastName:"Miller",
emailId:"kl12#gmail.com",
id:"02"
},
{
firstName:"Jhonathan",
lastName:"adam",
emailId:"jadm12#gmail.com",
id:"03"
},
{
firstName:"Lewis",
lastName:"harber",
emailId:"lewh12#gmail.com",
id:"04"
}
];
var approvedIds = ['01', '03'];
//Solution:
var newData = resData
.filter(rd => approvedIds.indexOf(rd.id) >= 0)
.map(rd => Object.assign({}, rd, {approvedStatus: "approved"}));
console.log(newData, resData);

Categories