JSON convert with Javascript [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a json file like as below
[{
"id": 2,
"name": "Ali",
"records":[{
"type": "L",
"total": 123
}, {
"type": "P",
"total": 102
}]
},{
"id": 3,
"name": "Mete",
"records":[{
"type": "O",
"total": 100
}, {
"type": "T",
"total": 88
}]
}]
I want to convert to like this
[{
"id": 2,
"name": "Ali",
record: {
"type": "L",
"total": 123
}
},{
"id": 2,
"name": "Ali",
record: {
"type": "P",
"total": 102
}
},{
"id": 3,
"name": "Mete",
record: {
"type": "O",
"total": 100
}
},{
"id": 3,
"name": "Mete",
record: {
"type": "T",
"total": 88
}
}]
how can i do it using javascript?

Here is what you could do. However, this doesn't work in IE as is as Object.assign that is being used, isn't yet supported in IE. However, it could be replaced with any javascript object clone methods.
You could check : What is the most efficient way to deep clone an object in JavaScript?
var input = [{
"id": 2,
"name": "Ali",
"records": [{
"type": "L",
"total": 123
}, {
"type": "P",
"total": 102
}]
}, {
"id": 3,
"name": "Mete",
"records": [{
"type": "O",
"total": 100
}, {
"type": "T",
"total": 88
}]
}];
var output = [];
input.forEach((obj) => {
var records = obj.records;
delete obj.records;
records.forEach((record) => {
// Doesnt have any support in IE.
var newRecord = Object.assign({}, obj);
newRecord.record = record;
output.push(newRecord);
});
});
console.log(output);
If you are fine to use jQuery, here is what you could do.
var input = [{
"id": 2,
"name": "Ali",
"records": [{
"type": "L",
"total": 123
}, {
"type": "P",
"total": 102
}]
}, {
"id": 3,
"name": "Mete",
"records": [{
"type": "O",
"total": 100
}, {
"type": "T",
"total": 88
}]
}];
var output = [];
input.forEach((obj) => {
var records = obj.records;
delete obj.records;
records.forEach((record) => {
var newRecord = jQuery.extend({}, obj);
newRecord.record = record;
output.push(newRecord);
});
});
console.log(output);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Here's a functional (but probably not very efficient) way of doing it:
function transform(data) {
// Merge the sub arrays together
return [].concat.apply([], (data.map(person => {
// Return an array of copied objects for each person
return person.records.map(record => {
// For each record, copy the person information
return {
id: person.id,
name: person.name,
record: record
};
});
})));
}
console.log(transform([{
"id": 2,
"name": "Ali",
"records":[{
"type": "L",
"total": 123
}, {
"type": "P",
"total": 102
}]
},{
"id": 3,
"name": "Mete",
"records":[{
"type": "O",
"total": 100
}, {
"type": "T",
"total": 88
}]
}]));

There's a few ways but Array.prototype.map seems to fit the bill. This blurb should get you started:
// We'll assume your original array is called myArray
var newArray = myArray.map ( function ( d ) {
return {
id : (d.id || 'theIDYouWant'),
name : (d.name || 'theNameYouWant' ),
record : { type : d.type, total : d.total }
}
} );
var jsonStr = JSON.stringify ( newArray );
console.log ( jsonStr ); // should write out your JSON as expected.

This will do it and save what you want in new_json
try running the code snippet below
json = [{
"id": 2,
"name": "Ali",
"records": [{
"type": "L",
"total": 123
}, {
"type": "P",
"total": 102
}]
}, {
"id": 3,
"name": "Mete",
"records": [{
"type": "O",
"total": 100
}, {
"type": "T",
"total": 88
}]
}]
new_json = [];
for (var i = 0; i < json.length; i++) {
for (j = 0; j < json[i]['records'].length; j++) {
new_json.push({
id: json[i]['id'],
name: json[i]['name'],
record: json[i]['records'][j]
})
}
}
console.log(new_json);

Related

Search inside child Array of objects with multiple value

Currently i have below Array of Objects
const dataClass = [
{
"id": 101,
"class": [
{
"type": "A",
"value": "A-class"
},
{
"type": "B",
"value": "B-class"
},
{
"type": "C",
"value": "C-class"
}
],
"rank": 1
},
{
"id": 102,
"class": [
{
"type": "D",
"value": "D-class"
},
{
"type": "E",
"value": "E-class"
},
{
"type": "F",
"value": "F-class"
}
],
"rank": 2
},
{
"id": 103,
"class": [
{
"type": "G",
"value": "G-class"
},
{
"type": "H",
"value": "H-class"
},
{
"type": "I",
"value": "I-class"
}
],
"rank": 3
}
];
i need to get dataClass object using all value inside the class object, let say i want to get the second object, so i have to search/input "type": "D", "type": "E", and "type": "F".
return array object/object i expect:
[{
"id": 102,
"class": [
{
"type": "D",
"value": "D-class"
},
{
"type": "E",
"value": "E-class"
},
{
"type": "F",
"value": "F-class"
}
],
"rank": 2
}]
I don't find any solution so far, Thanks for any help.
I added one more object with types D, E, F at rank 4
If you want to return all objects that match your filtration, check result1
and if you just wanna return the first object that matches, check result2
const dataClass = [
{
"id": 101,
"class": [
{
"type": "A",
"value": "A-class"
},
{
"type": "B",
"value": "B-class"
},
{
"type": "C",
"value": "C-class"
}
],
"rank": 1
},
{
"id": 102,
"class": [
{
"type": "D",
"value": "D-class"
},
{
"type": "E",
"value": "E-class"
},
{
"type": "F",
"value": "F-class"
}
],
"rank": 2
},
{
"id": 103,
"class": [
{
"type": "G",
"value": "G-class"
},
{
"type": "H",
"value": "H-class"
},
{
"type": "I",
"value": "I-class"
}
],
"rank": 3
},
{
"id": 104,
"class": [
{
"type": "D",
"value": "D-class"
},
{
"type": "E",
"value": "E-class"
},
{
"type": "F",
"value": "F-class"
}
],
"rank": 4
}
];
const expectedValues = ['D', 'E', 'F'];
//use this if you wanna return all objects that match expectedValues
const result1 = dataClass.filter(el => el.class.every(obj => expectedValues.includes(obj.type)));
console.log('all matched Objects => ', result1);
//use this if you wanna return the first object that match expectedValues
const result2 = dataClass.find(el => el.class.every(obj => expectedValues.includes(obj.type)));
console.log('first matched object => ',result2);
Hope this will help,
const dataClass = [
{
"id": 101,
"class": [
{
"type": "A",
"value": "A-class"
},
{
"type": "B",
"value": "B-class"
},
{
"type": "C",
"value": "C-class"
}
],
"rank": 1
},
{
"id": 102,
"class": [
{
"type": "D",
"value": "D-class"
},
{
"type": "E",
"value": "E-class"
},
{
"type": "F",
"value": "F-class"
}
],
"rank": 2
},
{
"id": 103,
"class": [
{
"type": "G",
"value": "G-class"
},
{
"type": "H",
"value": "H-class"
},
{
"type": "I",
"value": "I-class"
}
],
"rank": 3
}
];
const resultArr = [];
for (const ch_arr of dataClass){
for (const class_arr of ch_arr["class"]){
if(["D","E","F"].includes(class_arr["type"])){
resultArr.push(ch_arr);
break;
}
};
};
// resultArr is the expected array
You need find the object inside of class Array so i think using find method is the more readable way to solved it
function findClassByType(value: string) {
return [dataClass.find((obj) => obj.class.find(({ type }) => type.toLocaleLowerCase() === value.toLocaleLowerCase()))];
}
console.log(findClassByType('a'))
I added the toLocaleLowerCase to avoid case sensitive.

How to create a json object from two arrays in JavaScript

I have the following arrays
['a','b','c','d','e','f']
[1762, 770, 93, 474, 323, 351]
I would like to convert them into a list of json objects so that I end up with an object that looks a bit like this
{
"SomeObject": [
{
"name": "a",
"value": 1762
},
{
"name": "b",
"value": 770
},
{
"name": "c",
"value": 93
},
{
"name": "d",
"value": 474
},
{
"name": "e",
"value": 323
},
{
"name": "f",
"value": 351
}
]
}
How can I concert these arrays to the above object in JavaScript.
Thank you in advance
const keys = ['a','b','c','d','e','f'];
const values = [1762, 770, 93, 474, 323, 351];
const result = keys.map((key, i) => ({ name: key, value: values[i] }));
console.log(result);

Merge two objects when there's a new key

I have two objects with the following structure and tried to merge them together.
I tried it with $.merge but its not the expected result.
Object 1 - Has not all attributes
{
"id": 23,
"name": "Article",
"related": 15 "items": [{
"name": "Test1",
"items": [{
"name": "Test2",
"items": [{
"name": "Test3",
"items": [{
"name": "Test4",
"items": [{
"name": "Test5",
"items": [{
"name": "Test6",
}]
}]
}]
}]
}]
}]
}, {
"id": 24…
}
Object 2 - with additional attributes
{
"id": 23,
"name": "Article",
"related": 15 "items": [{
"name": "Test1",
"id": 34 "items": [{
"name": "Test2",
"id": 57 "items": [{
"name": "Test3",
"id": 92 "items": [{
"name": "THIS ONE IS NOT EXISTING IN OBJECT 1 AND SHOULD NOT GET MERGED",
"id": 789
}, {
"name": "Test4",
"id": 12 "items": [{
"name": "Test5",
"id": 321 "items": [{
"name": "Test6",
"id": 285
}]
}]
}]
}]
}]
}]
}, {
"id": 24…
}
Does anyone know some smart trick? Is jQuery even necessary?
jQuery's $.extend will do what you want.
//merging two objects into new object
var new_object = $.extend(true, {}, object1, object2);
//merge object2 into object1
$.extend(true, object1, object2);
The 1st parameter: deep:true, see: https://api.jquery.com/jquery.extend/
Without jquery: https://jsfiddle.net/sLhcbewh/
function mymerge_sub(object1, object2)
{
for(var i in object2) {
if(i == 'items')
continue;
console.log(i);
if(object1[i] === undefined) {
console.log(i + ' not found');
object1[i] = object2[i];
}
}
if(object1.items !== undefined) {
mymerge_sub(object1.items[0], object2.items[0])
}
}
function mymerge(object1, object2) {
var ret = JSON.parse(JSON.stringify(object1));
mymerge_sub(ret, object2); // save obj 1
return ret;
}
var obj3 = mymerge(obj1, obj2);
If you want several items, you have to loop mymerge_sub(object1.items[j]... ).

Get values from multi dimensional array

I have an array from which I want to get only names.
var peoples = [
{ "name": "dod", "class": "a", "age": 12 },
{ "name": "john", "class": "b", "age": 14 },
{ "name": "henry", "class": "c", "age": 23 }
];
How can I get the name from each object with comma separation?
In jquery,
var peoples = [
{ "name": "dod", "class": "a", "age": 12 },
{ "name": "john", "class": "b", "age": 14 },
{ "name": "henry", "class": "c", "age": 23 }
];
var names = new Array();
$.each(peoples,function(key,value){
names[key] = value.name;
});
namelist = names.join(",");
console.log(namelist);
http://jsfiddle.net/9344Q/
This will definitely do it in plain Javascript:
var peoples = [
{ "name": "dod", "class": "a", "age": 12 },
{ "name": "john", "class": "b", "age": 14 },
{ "name": "henry", "class": "c", "age": 23 }
];
var arr = [];
peoples.forEach(function(name) {
arr.push(name['name']);
});
console.log(arr.join(','));
var peoples = [
{ "name": "dod", "class": "a", "age": 12 },
{ "name": "john", "class": "b", "age": 14 },
{ "name": "henry", "class": "c", "age": 23 }
];
alert(peoples.map( function(v){ return v.name; }).join());

mongodb getting the oldest of animals map/reduce

I've never tried map/reduce.
How would I get the oldest of each type of animal?
My data is like this:
[
{
"cateory": "animal",
"type": "cat",
"age": 4,
"id": "a"
},
{
"cateory": "animal",
"type": "bird",
"age": 3,
"id": "b"
},
{
"cateory": "animal",
"type": "cat",
"age": 7
"id": "c"
},
{
"cateory": "animal",
"type": "bird",
"age": 4,
"id": "d"
},
{
"cateory": "animal",
"type": "cat",
"age": 8,
"id": "e"
},
{
"cateory": "company",
"type": "Internet",
"age": 5,
"id": "Facebook"
}
]
I'm using node-mongodb-native. Thanks!
Your map function should look something like this:
map = function() {
emit({type: this.type}, {age: this.age});
}
And the reduce function:
reduce = function(key, values) {
maxAge = 0;
values.forEach(function(v) {
if (maxAge < v['age']) {
maxAge = v['age'];
}
});
return {age: maxAge};
}
It's pretty simple:
collection.find({type : 'animal'}).sort({animal: -1}).limit(1);

Categories