This question already has answers here:
How can I get the full object in Node.js's console.log(), rather than '[Object]'?
(19 answers)
Closed 4 months ago.
I'm having data as shown below
{
"name": "test",
"records": [
{
"position": 1,
"data": {
"employees": {
"teams": [],
"users": []
},
"address": "ABC 123 Street"
}
},
{
"position": 2,
"data": {
"employees": {
"teams": [],
"users": []
},
"address": "DEF 456 Street"
}
}
]
}
Now I would like to get the address of all the records but when you see the output I'm getting it as [object]. So can anyone let me know how do I get the address ?
This is my code:
const fs= require('fs');
const { isObject } = require('util');
function jsonReader(filePath,cb){
fs.readFile(filePath, 'utf-8', (error, fileData) =>{
if(error){
return cb && cb(error);
}
try {
const mydata = JSON.parse(fileData);
return cb && cb(null,mydata);
} catch (error) {
return cb && cb(error);
}
});
}
jsonReader('./data.json',(error,data)=>{
if(error){
console.log(error);
}else{
console.log(data);
}
})
Output:
{
name: 'test',
records: [ { position: 1, data: [Object] }, { position: 2, data: [Object] } ]
}
Is this what you are looking for?
data = JSON.parse(`{
"name": "test",
"records": [{
"position": 1,
"data": {
"employees": {
"teams": [],
"users": []
},
"address": "ABC 123 Street"
}
},
{
"position": 2,
"data": {
"employees": {
"teams": [],
"users": []
},
"address": "DEF 456 Street"
}
}
]
}`);
addresses = data.records.map(record => record.data.address);
console.log(addresses)
Related
Here's the some code i try what I did
deleteajobewith_events(event){
const data =event.store.readQuery({
query: ClientJobesList,
variables: {id:1}
});
data.client.jobes.filter(jobee=>jobee.id != 101);
console.log(data);
event.store.writeQuery({ query: ClientJobesList, data});
}
If I console log the 'data', it shows the same data without filtering
this is a hint about the 'data' object
{
"data": {
"client": {
"id": "1",
"client_name": "Marouane",
"jobes": [
{
"id": "101",
"title": "cbkvjk",
"order": 88,
"client_id": "1"
},
.........
]
}
}
}
Filter creates new array, and data must be the same type (101 is not the same as "101") so try like following:
const data= {
"client": {
"id": "1",
"client_name": "Marouane",
"jobes": [
{
"id": "101",
"title": "cbkvjk",
"order": 88,
"client_id": "1"
},
{
"id": "102",
"title": "aaa",
"order": 99,
"client_id": "2"
},
]
}
}
data.client.jobes = data.client.jobes.filter(jobee=>jobee.id !== '101');
console.log(data)
u haven't assign filtered data to previous one :
deleteajobewith_events(event){
const data =event.store.readQuery({
query: ClientJobesList,
variables: {id:1}
});
data.client.jobes = data.client.jobes.filter(jobee=>jobee.id != 101);
console.log(data);
event.store.writeQuery({ query: ClientJobesList,
data});
}
I need to delete a location object from the locations array. It is deeply nested. I followed mongoose documentation but my attempts didn't work:
lists = [{
"listName": "Test",
"_id": "8d55f0afe545a0178c320706",
"listId": "5fd9a3bef6c39b2f9c4df65b",
"date": "12/15/2020",
"dueDate": "2020-11-18",
"items": [
{
"itemNumber": 123,
"description": "item123",
"onHand": 60,
"_id": "13dd1f26ecd2baeb61b3b455",
"locations": [
{
"locationName": "loc1",
"count": 10,
"_id": "50a2c969465ba8010bd48977"
},
{
"locationName": "loc2",
"count": 20,
"_id": "51c2f1d25311dc8fabdbf604a59b"
},
{
"locationName": "Loc3",
"count": 30,
"_id": "7cb0c1f51a91c384846d65f8b2ae"
}
]
},
{more lists}
Attempt:
router.post("/lists/deleteLoc", (req, res) => {
const {
listId,
list_id,
item_id,
location_id
} = req.body;
List.updateOne({
"lists.listId": listId,
"lists._id": list_id
}, {
$pull: {
"lists.$.items": {
locations: {
$elemMatch: {
_id: location_id
})
.then(() => res.json({
msg: "location removed"
}))
.catch((err) => res.status(400).json({
msg: "Error: " + err
}));
});
If the request location_id was "7cb0c1f51a91c384846d65f8b2ae" it should delete the last location from the array. The desired result:
lists = [{
"listName": "Test",
"_id": "8d55f0afe545a0178c320706",
"listId": "5fd9a3bef6c39b2f9c4df65b",
"date": "12/15/2020",
"dueDate": "2020-11-18",
"items": [
{
"itemNumber": 123,
"description": "item123",
"onHand": 60,
"_id": "13dd1f26ecd2baeb61b3b455",
"locations": [
{
"locationName": "loc1",
"count": 10,
"_id": "50a2c969465ba8010bd48977"
},
{
"locationName": "loc2",
"count": 20,
"_id": "51c2f1d25311dc8fabdbf604a59b"
}
]
},
{more lists}
I've tried basically all variations of this, but none have worked.
I'm also not sure if making a router.post or an axios.post request for deletion is correct. Should this be axios.delete and router.delete?
I've tried this in one of my similar DB and worked!
List.updateOne({ "listId": yourListId },
{
'$pull': {
'items.$[item].locations': { "_id": yourLocationId }
}
}, {
"arrayFilters": [
{
"item._id": yourItemId
}
]
}, function (err) {
if (err) {
res.json(err)
} else {
res.json({ message: "Updated" })
}
})
}
You've to put the values that're inside your DB from the object that you want to delete.
So if you want to delete the object with
"locationname" : "Loc3"
You should use
var yourListId = "5fd9a3bef6c39b2f9c4df65b";
var yourItemId = "13dd1f26ecd2baeb61b3b455";
var yourLocationId = "7cb0c1f51a91c384846d65f8b2ae";
Try it out!
I have this string:
const test = `
{
"name": "Error",
}
{
"name": "Signup Success",
"status": "400",
"body": {
"name": {
"first": "test",
},
"roles": [
"user"
],
"isMale": true,
}
}
`
How can i get what's inside the two objects separately. Like the first object contains "name": "Error" and the second object contains :
"name": "Signup Success",
"status": "400",
"body": {
"name": {
"first": "test",
},
"roles": [
"user"
],
"isMale": true,
}
You can build a parser:
const test = `
{
"name": "Error",
}
{
"name": "Signup Success",
"status": "400",
"body": {
"name": {
"first": "test",
},
"roles": [
"user"
],
"isMale": true,
}
}
`;
const addCommas = str => {
const charactersArray = Array.from(str.replace(/\s/g, ''));
charactersArray.reduce((acc, curr, index, self) => {
if (curr === '{') acc++;
if (curr === '}') acc--;
if (acc === 0 && curr === '}') self[index] = '},';
return acc;
}, 0);
return charactersArray.join('').replace(/,\}/g, '}').replace(/,$/, '');
};
const parsedObject = JSON.parse('['+addCommas(test)+']');
parsedObject.forEach((el, i) => {
console.log(`Element ${i+1} name: ${el.name}`);
});
This is 100% safe because also strings lile "}{" don't cause problems
If it's just in the format you've posted you may just split it with \n\n as separator:
let objects = test.split("\n\n")
And if resulting code is valid JSON (in example it's not valid) you may parse it:
let parsed = objects.map(JSON.parse)
A valid JSON would be:
const test = `
{
"name": "Error"
}
{
"name": "Signup Success",
"status": "400",
"body": {
"name": {
"first": "test"
},
"roles": [
"user"
],
"isMale": true
}
}
`
Use String#replace to get rid of trailing , (like: "name": {"first": "test",} after "test")
.replace(/,(\n*\s*)(})/g, "$2")
Then use String#split by targeting the space between } and { (notice Regex LookBehinds are not yet implemented everywhere)
.split(/(?<=})\n+(?={)/)
Then Array#map to transform each section in an object.
const test = `
{
"name": "Error",
}
{
"name": "Signup Success",
"status": "400",
"body": {
"name": {
"first": "test",
},
"roles": [
"user"
],
"isMale": true,
}
}
`
const [error, data] = test
.replace(/,(\n*\s*)(})/g, "$2")
.split(/(?<=})\n+(?={)/)
.map(raw=>JSON.parse(raw));
console.log(error, data);
I have nested array of object structure look like this
const resp = [
[
{
id: 1
"name": {
"en": {
"language": "en",
"value": "something"
},
"id": {
"language": "th",
"value": "something else"
}
}
}
]
]
I use ES6 to truncate the name property, base on 'en':
resp = resp.map(o => ({
...o,
o.map(o2 => ({ //unexpected token
...o2,
name: o2.name.en.value
})
)
})
)
But I got the unexpected token error?
I want to produce this result
//expected output
const resp = [
[
{
id: 1
name: "something"
}
]
]
const resp = [
[{
id: 1,
"name": {
"en": {
"language": "en",
"value": "something"
},
"id": {
"language": "th",
"value": "something else"
}
}
}]
];
const result = resp.map(o => {
return o.map(o2 => {
return {
id: o2.id,
name: o2.name.en.value
}
})
});
console.log(result);
This can also be achieved using Array.reduce() function, other than using Array.map() as #AushGupta has answer. The detailed description and answers are at MDN.
const resp = [
[
{
id: 1,
"name": {
"en": {
"language": "en",
"value": "something"
},
"id": {
"language": "th",
"value": "something else"
}
}
},
{
id: 3,
"name": {
"en": {
"language": "en",
"value": "newthing"
},
"id": {
"language": "th",
"value": "something else"
}
}
}
],
[
{
id: 2,
"name": {
"en": {
"language": "en",
"value": "something"
},
"id": {
"language": "th",
"value": "something else"
}
}
}
]
];
var result = resp.reduce((results, current) => {
var items = current.reduce((items, item) => {
items.push({
id: item.id,
name: item.name.en.value
});
return items;
}, []);
results.push(items);
return results;
}, []);
console.log(result);
<html>
<body>
</body>
</html>
Use .map on the array and you just need to return an object with id and name.
const resp = [
[
{
id: 1,
"name": {
"en": {
"language": "en",
"value": "something"
},
"id": {
"language": "th",
"value": "something else"
}
}
}
]
];
let result = resp[0].map(
el => {return {"id": el.id, "name": el.name.en.value}}
);
console.log(result);
You might need to wrap result in another array.
I want to build an new JSON from existing one. The source has sections and rubrics that I no longer need for a listing. The new object called 'items' should have an array of the items.
The final JSON should be sorted by attribute 'name' and look like
{
"items": [
{
"id": 10000006,
"name": "Boah"
},
{
"id": 10000013,
"name": "Gut"
},
{
"id": 10000003,
"name": "Ipsum"
},
{
"id": 10000001,
"name": "Lorem"
},
{
"id": 10000005,
"name": "Lorum"
},
{
"id": 10000004,
"name": "Name"
},
{
"id": 10000002,
"name": "Stet"
}
]
}
For building the new JSON I get this source:
{
"sections": [
{
"name": "FooBar",
"rubrics": [
{
"name": "Foo",
"items": [
{
"id": 10000001,
"name": "Lorem"
},
{
"id": 10000002,
"name": "Stet"
},
{
"id": 10000003,
"name": "Ipsum"
}
]
},
{
"name": "Bar",
"items": [
{
"id": 10000004,
"name": "Name"
},
{
"id": 10000005,
"name": "Lorum"
},
{
"id": 10000006,
"name": "Boah"
}
]
}
]
},
{
"name": "BlahBloob",
"rubrics": [
{
"name": "Bla",
"items": [
{
"id": 10000013,
"name": "Gut"
}
]
},
{
"name": "Bloob",
"items": [
{
"id": 10000014,
"name": "Name"
},
{
"id": 10000015,
"name": "Lorem"
}
]
}
]
}
]
}
What do you think? How can I do this with plain JavaScript or maybe TypeScript?
Thanks for reading and have time for my question. And thanks for reply in advance.
Here you go. You just need to iterate over each rubric of each section of your source to get the items. At the end, sort your list of items by items, and you're done.
This example uses ES6 syntax, but it's easy to convert it to ES5 if needed.
function extractItems(source) {
const items = [];
for (const section of source.sections) {
for (const rubric of section.rubrics) {
items.push(...rubric.items);
}
}
items.sort((a, b) => a.name.localeCompare(b.name));
return { items };
}
A more functional approach use map and reduce to pick the rubrics and merge them.
data.sections
.map(section => section.rubrics) // get rubrics
.reduce((a, b) => a.concat(b)) // merge rubrics
.map(rubric => rubric.items) // get items from each rubric
.reduce((a, b) => a.concat(b)) // merge items
.sort((a, b) => a.name.localeCompare(b.name)); // sort
function(oldObj) {
var newObj = {
"items": []
};
oldObj.sections.forEach(function(section) {
section.rubrics.forEach(function(rubric) {
rubric.items.forEach(function(item) {
newObj.items.push(item);
});
});
});
newObj.items = newObj.items.sort(function(a, b) {
if (a.name < b.name) { return -1; }
if (a.name > b.name) { return 1; }
return 0;
});
return newObj;
}
And simply use JSON.parse() and JSON.stringify() to convert JSON to and from objects.
It might help you
var data ={
"sections": [
{
"name": "FooBar",
"rubrics": [{"name": "Foo", "items": [{"id": 10000001,"name": "Lorem"}, {"id": 10000002,"name": "Stet"}, {"id": 10000003,"name": "Ipsum"}]
}, {
"name": "Bar",
"items": [{
"id": 10000004,
"name": "Name"
}, {
"id": 10000005,
"name": "Lorum"
}, {
"id": 10000006,
"name": "Boah"
}]
}]
}, {
"name": "BlahBloob",
"rubrics": [{
"name": "Bla",
"items": [{
"id": 10000013,
"name": "Gut"
}]
}, {
"name": "Bloob",
"items": [{
"id": 10000014,
"name": "Name"
}, {
"id": 10000015,
"name": "Lorem"
}]
}]
}]
};
var itemObj = {};
var itemArr = [];
var sections = data.sections;
for(var i=0;i<sections.length;i++)
{
for(var j=0;j<sections[i].rubrics.length;j++){
for(var k=0;k<sections[i].rubrics[j].items.length;k++){
var itemObj;
itemObj['id'] = sections[i].rubrics[j].items[k].id;
itemObj['name'] = sections[i].rubrics[j].items[k].name;
itemArr.push(itemObj);
}
}
}
var finalObj = {"items":itemArr};
console.log(finalObj);
JSFiddle