How can i get pair of the json object in javascript - javascript

data =
{"user" : [
{
"id" : 1,
"name" : "jeboo",
"level": 1
},
{
"id" : 2,
"name" : "yoyo",
"level": 1
},
{
"id" : 3,
"name" : "yaya",
"level": 2
},
{
"id" : 4,
"name" : "yeye",
"level": 2
},
{
"id" : 5,
"name" : "yiyi",
"level": 3
},
{
"id" : 6,
"name" : "jebee",
"level": 3
}
]}
this is how i get json object
var obj = JSON.stringify(data);
var parse = JSON.parse(obj);
$.each(parse, function(key, object) {
$.each(object, function(index, val) {
console.log(index, val);
});
});
my purpose is want to produce the array below
object 0 + object 1 = first pair
object 2 + object 3 = second pair
object 4 + object 5 = third pair

Assuming you want objects with same level in pairs,
You can use Array#reduce to achieve this:
var data =
{"user" : [
{
"id" : 1,
"name" : "jeboo",
"level": 1
},
{
"id" : 2,
"name" : "yoyo",
"level": 1
},
{
"id" : 3,
"name" : "yaya",
"level": 2
},
{
"id" : 4,
"name" : "yeye",
"level": 2
},
{
"id" : 5,
"name" : "yiyi",
"level": 3
},
{
"id" : 6,
"name" : "jebee",
"level": 3
}
]};
var r = data.user.reduce(function(res, obj) {
res[obj.level - 1] = res[obj.level - 1] || [];
res[obj.level - 1].push(obj);
return res;
}, []);
console.log(r);
EDIT
If you want to pair the objects according to their position in the array and independent of level property then you can use callback's index argument and a bit of math:
var r = data.user.reduce(function(res, obj, idx) {
res[Math.floor(idx/2)] = res[Math.floor(idx/2)] || [];
res[Math.floor(idx/2)].push(obj);
return res;
}, []);

Related

Getting empty data while trying to get desired format of object

I have an object
"data" : [
{
"name" : "Heading",
"text" : "Text Heading",
"type" : "string",
"values" : [
"Arthur"
]
},
{
"name" : "Source",
"text" : "Source Reference",
"type" : "string",
"values" : [
"Jhon"
]
},
{
"name" : "Place",
"text" : "Bank Building",
"type" : "string",
"values" : [
"Mark"
]
},
{
"name" : "Animal",
"text" : "Branch",
"type" : "string",
"values" : [
"Susan"
]
}
]
there is a function i am passing the object and an array as the arguments
fieldArray=["Heading", "Animal"]
myFunction(fieldArray, data){
... your code here
}
I need to get the output in the below format where I have to search the object with the fields in myArray with the name key of data. Then I need to put the value of the searched object in the below format
[{
"id": 1,
"cells": [{
"id": "ConstId",
"cellContent": "Heading"
},
{
"id": "ConstValue",
"cellContent": "Arthur"
}
]
},
{
"id": 2,
"cells": [{
"id": "ConstId",
"cellContent": "Animal"
},
{
"id": "ConstValue", //a constant field name as ConstValue
"cellContent": "Susan" // the value of the second field in the myArray from object with name Animal
}
]
}
]
I have tried this
const getFormattedData = (fieldArray: any, data: any) => {
let innerData: any = [];
for (let i=0; i<fieldArray.length; i++){
const indexNumber = data.find((key: any) => key.name === fieldArray[i])
if(indexNumber != undefined){
innerData.push({
id: i+1,
cells:[{
id: 'inquiryName',
cellContent: indexNumber.name
},
{
id: 'value',
cellContent: indexNumber.values.toString()
}
]
})
}
console.log('innerData :>> ', innerData);
}
}
You could use the below. Since you tagged javascript, posting answer in JS.
function formatData(data, fieldArray) {
let ret = [];
fieldArray.forEach((field, i) => {
let dataObj = data.filter(d => d.name === field)[0]
if( dataObj ) {
ret.push({
"id": 1,
"cells": [{
"id": "ConstId",
"cellContent": field
},
{
"id": "ConstValue",
"cellContent": dataObj.values[0] //Put whole obj or just first
}
]
})
}
})
return ret;
}
Link to plnkr

How to display all fields of a nested json in table format using Bootstrap

I want to write a utility which connects to a REST api downloads data in JSON format and then paints the data as nested tables using Bootstrap.
JSON Data -
[
{
"id" : "Id1",
"name" : "Name1",
"orders" : [{"orderId" : "o1", "size" : 34}, {"orderId" : "o2", "size" : 3}]
},
{
"id" : "Id2",
"name" : "Name2",
"orders" : [
{"orderId" : "o3", "size" : 5, "addresses" : [{"addressId" : "a1", "phone" : "1235"}, {"addressId" : "a2", "phone" : 555}]},
{"orderId" : "o4", "size" : 5, "addresses" : [{"addressId" : "a3", "phone" : "1235"}]}
]
}
]
I looked at the sub-table feature of Bootstrap, however it seems that it would need lot of custom code to get this working. Is there a better way to bind the json to table in a generic way?
Edit
After spending some time I was able to achieve this -
As you can see, I could get one level of nesting, however i just need to go one level deep. Any suggestions?
<script>
var $table = $('#table')
function buildTable($el, jsonData) {
var i; var j; var row
var columns = []
var data = []
if(!Array.isArray(jsonData) && jsonData.length == 0) {
return;
}
Object.keys(jsonData[0]).forEach( (k) => {
columns.push({
field: k,
title: k,
sortable: true
})
})
for(var j = 0; j < jsonData.length; j++) {
row = {}
Object.keys(jsonData[j]).forEach( (k) => {
row[k] = jsonData[j][k]
})
data.push(row)
}
$el.bootstrapTable({
columns: columns,
data: data,
detailFilter: function (index, row) {
console.log("detail filter " + Object.values(row))
for(var k in row) {
if(Array.isArray(row[k])){
return true;
}
}
return false;
},
onExpandRow: function (index, row, $detail) {
console.log("expand row keys " + Object.keys(row))
console.log("expand row vals " + Object.values(row))
var newRow = {};
for(var k in row) {
if(Array.isArray(row[k])){
alert('found ' + row[k])
newRow = row[k]
break
}
}
buildTable($detail.html('<table></table>').find('table'), newRow)
}
})
};
var mydata =
[
{
"id": 0,
"name": "test0",
"price": "$0",
"orders" :
[
{
"name" : "ABC",
"size" : 25,
"someList": [{"a":1, "b":2}, {"a":3, "b":4}]
},
{
"name" : "XYZ",
"size" : 50
}
]
}
/* {
"id": 1,
"name": "test1",
"price": "$1"
},
{
"id": 2,
"name": "test2",
"price": "$2",
"orders" : [{"name" : "def", "size": 45}]
}*/
];
$(function() {
buildTable($table, mydata)
})

Access title inside id

I am having trouble to access title inside an ID object.
I want to access item.title. But i am not able to give a name to the object ID.
I tried doing order.cart.items.item.title
"_id" : ObjectId("5d60d1752cda6403e4f868af"),
"created_at" : ISODate("2019-08-24T05:55:34.741Z"),
"user" : ObjectId("5d60d00e4c865312ccf3f18a"),
"cart" : {
"items" : {
"5d60cddb69f460191c680e96" : {
"item" : {
"_id" : "5d60cddb69f460191c680e96",
"imagePath" : "https://dks.scene7.com/is/image/GolfGalaxy/18NIKWRMX270XXXXXLFS_Black_Cream?wid=1080&fmt=jpg",
"title" : "Nike ",
"description" : "Nike Airmax",
"price" : 10,
"category" : "shoes",
"__v" : 0
},
"qty" : 1,
"price" : 10
}
},
"totalQty" : 1,
"totalPrice" : 10
},
You need to use Object.values for that, because of the ID. This allows you to get the object with the key of 5d60cddb69f460191c680e96 without the key:
Object.values(order.cart.items)[0].item.title
const data = {
"cart" : {
"items" : {
"5d60cddb69f460191c680e96" : {
"item" : {
"_id" : "5d60cddb69f460191c680e96",
"imagePath" : "https://dks.scene7.com/is/image/GolfGalaxy/18NIKWRMX270XXXXXLFS_Black_Cream?wid=1080&fmt=jpg",
"title" : "Nike ",
"description" : "Nike Airmax",
"price" : 10,
"category" : "shoes",
"__v" : 0
},
"qty" : 1,
"price" : 10
}
},
"totalQty" : 1,
"totalPrice" : 10
}};
for (let id in data.cart.items)
console.log(data.cart.items[id].item.title);
You can simply achieve this by getting key name of an object using Object.keys() methods, This methods returns an array of key names
const obj = { id: 1 };
const keysArray = Object.keys(obj);
console.log(keysArray);. // ["id"]
In your case only one keys are present in the object, So we can directly get that name with index 0 (Object.keys(obj)[0])
Check below snippet
const cart ={
"items": {
"5d60cddb69f460191c680e96": {
"item": {
"_id":
"5d60cddb69f460191c680e96",
"imagePath": '',
"title": "Nike ",
"description": "Nike",
"price": 10,
"category": "shoes",
"__v": 0
},
"qty": 1,
"price": 10
}
}
};
const id =
Object.keys(cart.items)[0];
console.log(
cart.items[id].item.title
);

object transformation with underscore.js

For whatever reason, I have quite a bit of difficulty when trying to transform objects and arrays.
The current data I have is stored in a mongodb collection and looks like this:
[{ "_id" : 1, "name" : "someName", "colorName" : "Pink"},
{ "_id" : 2, "name" : "someName2", "colorName" : "RoyalBlue"},
{ "_id" : 3, "name" : "aThirdOne", "colorName" : "Gold"},
{ "_id" : 4, "name" : "oneMore", "colorName" : "LightGreen"}]
I need to get either the following two arrays, but would like to know how to get both.
[{ "value" : 1, "label" : "someName"},
{ "value" : 2, "label" : "someName2"},
{ "value" : 3, "label" : "aThirdOne"},
{ "value" : 4, "label" : "oneMore"]
[{1 : "someName"},
{2 : "someName2"},
{3 : "aThirdOne"},
{4 : "oneMore"}]
I know it is probably something with _.map, but I am not sure why I can't figure it out. Please advise.
You don't really need Underscore for this, it's just normal Array.prototype.map method usage (although Underscore also provides this method):
var data = [{ "_id" : 1, "name" : "someName", "colorName" : "Pink"},
{ "_id" : 2, "name" : "someName2", "colorName" : "RoyalBlue"},
{ "_id" : 3, "name" : "aThirdOne", "colorName" : "Gold"},
{ "_id" : 4, "name" : "oneMore", "colorName" : "LightGreen"}];
var result = data.map(function(el, i) {
return {value: el._id, label: el.name};
});
document.body.innerHTML = '<pre>' + JSON.stringify(result, null, 4) + '</pre>';
Also note, that your second data structure doesn't make sense because it's irregular, so don't use it, it's not very convenient at all.
And here is corresponding Underscore version:
// Or Underscore version
var result = _.map(data, function(el) {
return {value: el._id, label: el.name};
});
In plain Javascript you can use Array.prototype.forEach() for iteration througt the array and assembling the objects and push it to the wanted results.
The forEach() method executes a provided function once per array element.
var array = [{ "_id": 1, "name": "someName", "colorName": "Pink" }, { "_id": 2, "name": "someName2", "colorName": "RoyalBlue" }, { "_id": 3, "name": "aThirdOne", "colorName": "Gold" }, { "_id": 4, "name": "oneMore", "colorName": "LightGreen" }],
result1 = [],
result2 = [];
array.forEach(function (a) {
result1.push({ value: a._id, label: a.name });
var o = {};
o[a._id] = a.name
result2.push(o);
});
document.write('<pre>' + JSON.stringify(result1, 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(result2, 0, 4) + '</pre>');
use:
var newObject = _.map(yourObject, function(val) {
return {
"value": val._id,
"label": val.name
}});
And the same concept for the other result you're interested in .

mongodb update on JSON array

I have this data in Mongo:
{'_id':1,
'name':'Root',
'taskId':1,
'parentId':"",
'path':[1],
'tasks':[ {"taskId":3,parentId:1,name:'A',type:'task'},
{"taskId":4,parentId:1,name:'D',type:'task'},
{"taskId":5,parentId:4,name:'B',type:'task'},
{'type':'project' , 'proRef':2},
{"taskId":6,parentId:3,name:'E',type:'task'},
{"taskId":7,parentId:6,name:'C',type:'task'}]
}
Now I want to update taskId 6 with new Json data .
var jsonData = {"taskId":6,"name":'Sumeet','newField1':'Val1','newField2':'Val2'}
query should update if field is available else add new key to existing .Output Like
{"taskId":6,parentId:3,name:'Sumeet',type:'task','newField1':'Val1','newField2':'Val2'}]
I have tried few query but it is completely replacing json .
db.projectPlan.update({_id:1,'tasks.taskId':6},{$set :{'tasks.$':jsonData }});
Thanks in advance for your helps!
Sumeet
You need to transform the jsonData variable into something that can be passed to update. Here's an example that does exactly what you want with your sample document:
var updateData = {};
for (f in jsonData) {
if (f != "taskId") updateData["tasks.$."+f]=jsonData[f];
};
db.projectPlan.update({_id:1, 'tasks.taskId':6}, {$set:updateData})
Result:
{ "_id" : 1,
"name" : "Root",
"taskId" : 1,
"parentId" : "",
"path" : [ 1 ],
"tasks" : [
{ "taskId" : 3, "parentId" : 1, "name" : "A", "type" : "task" },
{ "taskId" : 4, "parentId" : 1, "name" : "D", "type" : "task" },
{ "taskId" : 5, "parentId" : 4, "name" : "B", "type" : "task" },
{ "type" : "project", "proRef" : 2 },
{ "taskId" : 6, "parentId" : 3, "name" : "Sumeet", "type" : "task", "newField1" : "Val1", "newField2" : "Val2" },
{ "taskId" : 7, "parentId" : 6, "name" : "C", "type" : "task" }
] }
You will need to merge the document manually:
var jsonData = {"taskId":5,"name":'Sumeet','newField1':'Val1','newField2':'Val2'};
db.projectPlan.find({ _id: 1 }).forEach(
function(entry) {
for (var taskKey in entry.tasks) {
if (entry.tasks[taskKey].taskId === jsonData.taskId) {
printjson(entry.tasks[taskKey]);
for (var taskSubKey in jsonData) {
entry.tasks[taskKey][taskSubKey] = jsonData[taskSubKey];
}
printjson(entry.tasks[taskKey]);
}
}
db.projectPlan.save(entry);
}
);
Obviously you can leave away the printjson statements. This is simply to see that the merging of the original tasks with the new tasks works. Note that this query will only update a single document as long as the _id field is unique.

Categories

Resources