get what's inside an object in a string - javascript

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);

Related

Get object details in nested array [duplicate]

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)

Transform JavaScript Object - JavaScript

I have a simple JavaScript nested object as shown below. I don't know how many children will be there, but that's how the nature of the data is that I am receiving.
How can I transform into expected result ?
Raw Data nested json
{
"work": {
"children": {
"abc": {
"label": "Work address",
"name": "address"
},
"xyz": {
"label": "Work phone",
"name": "phone"
},
"efg": {
"children": {
"position": {
"label": "Work",
"name": "position"
},
"employees": {
"label": "Number of employees",
"name": "employees"
}
}
}
}
}
}
Expected
{
work: {
"address": "",
"phone": "",
"details": {
"position": "",
"employees": ""
}
}
}
What I have tried is the following code
var jsonschema = root.json
var newjson = {}
for (let name in jsonschema) {
if (jsonschema.children.length > 0 ) {
//add a empty object to newjson
}
}
You could use a generic map function and a recursive transform function -
const map = (f, t) =>
Object.fromEntries(Object.entries(t).map(([ k, v ]) => [ k, f(v) ]))
const transform = (t = {}) =>
t.name
? ""
: map(transform, t.children || t)
const input =
{"work":{"children":{"address":{"component":"BaseInput","label":"Work address","name":"address"},"phone":{"component":"BaseInput","label":"Work phone","name":"phone"},"details":{"children":{"position":{"component":"BaseInput","label":"Work position","name":"position"},"employees":{"component":"BaseInput","label":"Number of employees","name":"employees"}}}}}}
console.log(transform(input))

How can i remove object from nested array?

I have this kind of json.
let arr1 = [
{
"packageReference": "1234",
"displayName": "Business",
"description": "Includes...",
"promotion": {
"packageReference": "1234",
"displayName": "$100 Standard",
"optionGroup": [
{
"displayName": "Access",
},
{
"displayName": "Contract"
},
{
"displayName": "Equipment"
},
{
"displayName": "Features"
},
{
"displayName": "Fees",
}
]
}
}
]
I need to remove only the object in the arr1[0].promotion.optionGroup where the displayName is 'Fees' and to return the new object without him.
You could do it by filtering the sub array like so:
let arr1 = [
{
"packageReference": "1234",
"displayName": "Business",
"description": "Includes...",
"promotion": {
"packageReference": "1234",
"displayName": "$100 Standard",
"optionGroup": [
{
"displayName": "Access",
},
{
"displayName": "Contract"
},
{
"displayName": "Equipment"
},
{
"displayName": "Features"
},
{
"displayName": "Fees",
}
]
}
}
];
arr1 = arr1.map(e => {
e['promotion']['optionGroup'] =
e['promotion']['optionGroup'].filter(s => s['displayName'] != 'Fees');
return e;
});
console.log(arr1);
// Get new array without the Fees one
const newGroup = arr1[0].promotion.optionGroup.filter(group => group.displayName !== 'Fees');
// Put new group into the object
arr1[0].promotion.optionGroup = newGroup;
Could also do it without creating a variable, but added it for cleanness.

How to check how many times a word shows up in JSON array

My JSON array looks like this:
{
"messages": [
{
"msg": "?",
"name": "johndoe"
},
{
"msg": "hello",
"name": "johndoe",
},
{
"msg": "twitt",
"name": "johndoe"
},
{
"msg": "hello everyone!",
"name": "johndoe"
},
{
"msg": "hello! how are you",
"name": "johndoe"
},
{
.........
I would like to know how I can check how many times the word "hello" shows up in this whole array, and then just return the number. Thank you for the help.
let helloCount = data.messages.filter(message=>{return message.msg.includes('hello')}).length;
Try above one
You can use reduce
const arr = {
"messages": [{
"msg": "?",
"name": "johndoe"
},
{
"msg": "hello",
"name": "johndoe",
},
{
"msg": "twitt",
"name": "johndoe"
},
{
"msg": "hello everyone!",
"name": "johndoe!!"
},
{
"msg": "hello! how are you",
"name": "johndoe!"
}
]
};
const count = arr.messages.reduce((acc, m) => {
if (m.name === "johndoe") {
acc += 1;
}
return acc;
}, 0);
console.log(count)
//shorter version
const count2 = arr.messages.reduce((acc, m) => m.name === "johndoe" ? acc += 1 : acc, 0);
console.log(count2)
// EDIT : if you wanna search for "johndoe" string and the name value is "johndoe!!"
const count3 = arr.messages.reduce((acc, m) => {
if (m.name.includes("johndoe")) {
acc += 1;
}
return acc;
}, 0);
console.log(count3)
You need the following.
data.forEach(ele => {if(ele.msg.includes('hello')) counter++ });
Here is a demo https://onecompiler.com/javascript/3v2spaetr
Since it it's a valid JSON format it may as well be treated as a string (before parsing) if that's the case a simple regex would be enough to count the occurrences of particular string inside of it
const input = `{
"messages": [
{
"msg": "?",
"name": "johndoe"
},
{
"msg": "hello",
"name": "johndoe",
},
{
"msg": "twitt",
"name": "johndoe"
},
{
"msg": "hello everyone!",
"name": "johndoe"
},
{
"msg": "hello! how are you",
"name": "johndoe"
}
]
}`;
function count(input, match){
return (input.match(new RegExp(match, "g")) || []).length;
}
console.log("hello: ", count(input, "hello"));
console.log("johndoe: ", count(input, "johndoe"));

transform property using map failed got unexpected token error

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.

Categories

Resources