Get the value of an object in Javascript [duplicate] - javascript

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
How can I access object properties containing special characters?
(2 answers)
Closed 2 years ago.
I was using wit.ai's JSON to get the data and recently they changed the structure. This is how it looks
"entities": {
"paraName:paraName": [
{
"id": "1266de86-97af-434b-95ee-f87ff58c935a",
"name": "paraName",
"role": "paraName",
"start": 30,
"end": 34,
"body": "data",
"confidence": 0.549,
"entities": [
],
"suggested": true,
"value": "data",
"type": "value"
},
{
"id": "1266de86-97af-434b-95ee-f87ff58c935a",
"name": "paraName",
"role": "paraName",
"start": 39,
"end": 45,
"body": "height",
"confidence": 0.8922,
"entities": [
],
"value": "height",
"type": "value"
}
]
}
This is how I am trying to get the value of those parameters (i.e. data, and height)
let data = response.entities;
let paraMeter = data.paraName.map(function(res){
return res['value'];
})
keyValues = paraMeter.join().split(',');
but I am getting Cannot read property 'map' of undefined error. Anyone knows what's wrong here?
Thank you

You can refer the key like shown in this snippet:
let paraMeter = data["paraName:paraName"].map(function(ref){
More details here :
Properties of JavaScript objects can also be accessed or set using a
bracket notation (for more details see property accessors). Objects
are sometimes called associative arrays, since each property is
associated with a string value that can be used to access it.
let response = {"entities": {
"paraName:paraName": [
{
"id": "1266de86-97af-434b-95ee-f87ff58c935a",
"name": "paraName",
"role": "paraName",
"start": 30,
"end": 34,
"body": "data",
"confidence": 0.549,
"entities": [
],
"suggested": true,
"value": "data",
"type": "value"
},
{
"id": "1266de86-97af-434b-95ee-f87ff58c935a",
"name": "paraName",
"role": "paraName",
"start": 39,
"end": 45,
"body": "height",
"confidence": 0.8922,
"entities": [
],
"value": "height",
"type": "value"
}
]}
};
let data = response.entities;
let paraMeter = data["paraName:paraName"].map(function(ref){
return ref['value'];
})
keyValues = paraMeter.join().split(',');
console.log(keyValues);

Related

Filter array of specific objects

How to use filter or forEach in javascript to output only the objects whithout parentId and the objects with only the first level of parentId.
Should output objects with ids: 1681, 1682, and 1683.
Should not output objects with ids: 1685, 1686 and 1687.
array = [ {
"id": 1681,
"label": "1",
"url": "page1",
},
{
"id": 1682,
"label": "2",
"url": "page1",
},
{
"id": 1683,
"label": "a",
"url": "page1",
"parentId": 1681,
},
{
"id": 1685,
"label": "aa",
"url": "page1",
"parentId": 1683,
},
{
"id": 1686,
"label": "aaa",
"url": "page1",
"parentId": 1683,
},
{
"id": 1687,
"label": "aaaa",
"url": "page1",
"parentId": 1683,
}
]
Something like this...
array.filter(({item}) => !item.parentId ? item.id : item.parentId)
We have to save the information if we already found a parentId from inside the filter function. A handy way to do this is by using the prefix operator ++ on a counter. This way we get around an explicit, long assignment with =. Instead we make it before.
Additionally with destructuring assignment we can extract the parentId comfortably of the array items and write a really short filter:
array=[{id:1681,label:"1",url:"page1"},{id:1682,label:"2",url:"page1"},{id:1683,label:"a",url:"page1",parentId:1681},{id:1685,label:"aa",url:"page1",parentId:1683},{id:1686,label:"aaa",url:"page1",parentId:1683},{id:1687,label:"aaaa",url:"page1",parentId:1683}];
window.parentIdCount = 0;
window.filtered =
array.filter(({parentId}) => !parentId || ++parentIdCount <= 1)
console.log(filtered)
Something like this ought to work:
const result = array.filter(object => object.parentId === undefined);

Parse json object and read values

I want to be able to parse this json tree and get the value of the attribute checked for every element :
{
"children": [
{
"children": [
{
"children": [],
"id": 49,
"name": "nice",
"checked": true,
"level": 3,
"path": "0_1_0_0",
"lineLength": 180
}
],
"id": 48,
"name": "amira",
"checked": false,
"level": 2,
"path": "0_1_0"
}
],
"id": 47,
"name": "mahdi",
"checked": true,
"level": 1,
"path": "0_1"
}
I'm able to read the data this way :
var data = this.flatData;
I want to be able to read the checked attribute for every child inside a for loop or a foreach and if it's true set a certain behaviour to my code do any one know how to do this and thanks in advance.
You can use a recursion; in your particular structure something like:
const func = (elem) => {
if (elem.children) elem.children.forEach((elem) => func(elem));
if (elem.checked) console.log(`act on elem with id: ${elem.id}`);
}
func(test);

Object Filter Using JS [duplicate]

This question already has answers here:
Extract certain properties from all objects in array
(5 answers)
Closed 1 year ago.
I am trying to filter selected property from object using JavaScript.
This is my array
const odata=[
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
},
{
"id": "0002",
"type": "ansd",
"name": "EARK",
"ppu": 0.67,
}
];
I want output like this - I want to select only 2 (id,type) props from the object
[
{"id": "0001","type": "donut"}
{"id": "0002","type": "ansd"}
]
We can use Array.map and some Destructuring to get the desired result.
The destructuring assignment syntax allows us to get selected values from Objects and Arrays in a convenient way.
const odata= [ { "id": "0001", "type": "donut", "name": "Cake", "ppu": 0.55, }, { "id": "0002", "type": "ansd", "name": "EARK", "ppu": 0.67, } ];
const result = odata.map(({ id, type}) => ({ id, type }));
console.log("Result:", result)
User Array.prototype.map() for generating a new array from an existing one.
Reference
const odata = [
{ "id": "0001", "type": "donut", "name": "Cake", "ppu": 0.55 },
{ "id": "0002", "type": "ansd", "name": "EARK", "ppu": 0.67 }
];
const output = odata.map(node => ({
id: node.id,
type: node.type,
}))
console.log(output)

Accessing a specific key in JSON?

I'm trying to access the "title" section (key?) of this JSON object using NodeJS. I can return the entire object, but every time I try to access the key, undefined is returned.
[
[
{
"id": 119,
"title": "Roadhouse",
"url": "https://funsite.com/2021/03/20/funny/",
"date": "2021-03-20"
}
],
[
{
"id": 208,
"title": "New Sites",
"url": "https://coolsitestuff.com/notes/coolsite/",
"date": "2021-03-17"
}
],
[
{
"id": 13,
"title": "woah sites!!",
"url": "https://now.lettuce.com/then/2021-0000/",
"date": "2021-03-07"
}
],
[
{
"id": 120,
"title": "mynewalbumn",
"url": "https://notarealsite.com/2021/03/06/next-album/",
"date": "2021-03-06"
}
],
[
{
"id": 140,
"title": "fightingthemans",
"url": "http://fightcats.com/2021/03/06/keyfights",
"date": "2021-03-06"
}
],
[
{
"id": 14,
"title": "biggest lettuce youll ever see",
"url": "https://morelettuce.com/then/biggestlettuceleaf/",
"date": "2021-02-28"
}
]
]
NodeJS
const fs = require('fs')
fs.readFile('./data/links.json', 'utf8', (err, fsToString) => {
let data = JSON.parse(fsToString);
console.log(data.map(link => link[link.url]))
})
I've tried for loops and indexing that way but I haven't been able to get anything out of it.
You have 2 arrays, either loop over both of them or access it using index
let data =[
[
{
"id": 119,
"title": "Roadhouse",
"url": "https://funsite.com/2021/03/20/funny/",
"date": "2021-03-20"
}
],
[
{
"id": 208,
"title": "New Sites",
"url": "https://coolsitestuff.com/notes/coolsite/",
"date": "2021-03-17"
}
]
]
data.map(link=> console.log(link[0].url))
Your json is array of array objects, you need to access all arrays by index, you can use flatMap and map methods.
var data = [
[{
"id": 119,
"title": "Roadhouse",
"url": "https://funsite.com/2021/03/20/funny/",
"date": "2021-03-20"
}],
[{
"id": 208,
"title": "New Sites",
"url": "https://coolsitestuff.com/notes/coolsite/",
"date": "2021-03-17"
}],
[{
"id": 13,
"title": "woah sites!!",
"url": "https://now.lettuce.com/then/2021-0000/",
"date": "2021-03-07"
}],
[{
"id": 120,
"title": "mynewalbumn",
"url": "https://notarealsite.com/2021/03/06/next-album/",
"date": "2021-03-06"
}],
[{
"id": 140,
"title": "fightingthemans",
"url": "http://fightcats.com/2021/03/06/keyfights",
"date": "2021-03-06"
}],
[{
"id": 14,
"title": "biggest lettuce youll ever see",
"url": "https://morelettuce.com/then/biggestlettuceleaf/",
"date": "2021-02-28"
}]
];
console.log(data.flatMap(i=>i.map(f=>f.url)))
Your current code is trying to access an undefined object property.
Solution:
Replace the link[link.url] for link[0].url. So that the full line is
console.log(data.map(link => link[0].url))
Or if you want the titles:
console.log(data.map(link => link[0].title))
console.log(
data.flat().map(link=>link.url)
);
console.log(
data.map(item=>item[0].url)
);
From what I see your JSON file holds an array of arrays and each nested array contains one object. Therefore data.map(link => link[0].title) should return array of titles
You have an array of arrays and each one with just one position. For the code you posted you're just missing the index of each element.
If you change your code to this you'll get the array with the URL's you're looking for
fs.readFile('./example.json', 'utf8', (err, fsToString) => {
let data = JSON.parse(fsToString);
console.log(data.map(link => link[0].url))
})
Happy coding ;)!

Using Lodash to transform data into object properties instead of a collection by specifying properties value

following up on my previous question about transforming data using lodash, this time i require output to be an object properties instead of being a collection. I appreciate the help and if someone can also guide me where to begin properly so i have a better understanding of these concepts
Sample Data
{
"changeAccount": {
"add": [
{
"changeType": 1,
"type": "changeAccount",
"updated": {
"id": 71,
"company": 124201,
"user": 8622
}
}
],
"remove": [
{
"changeType": 2,
"type": "changeAccount",
"updated": {
"id": 70,
"company": 124201,
"user": 8622
}
}
]
},
"changeproduct": {
"add": [
{
"changeType": 1,
"type": "changeproduct",
"updated": {
"id": 15,
"company": 124201,
"user": 8622
}
}
],
"remove": []
}
}
Expected Result
var sample = [{
"changeType": 1,
"type": "changeAccount",
"updated": {
"id": 71,
"company": 124201,
"user": 8622
}
},
{
"changeType": 2,
"type": "changeAccount",
"updated": {
"id": 70,
"company": 124201,
"user": 8622
}
},
{
"changeType": 1,
"type": "changeproduct",
"updated": {
"id": 15,
"company": 124201,
"user": 8622
}
}
]
Here is one way to do it:
chain(data)
.values()
.map(_.values)
.flatMapDeep()
.value()
So what's happening here is:
Start with our data which is an object
Use .values to return only the values of our top level properties (i.e. strip away changeProduct and changeAccount
Map the resulting items in the array to only the values of our objects (i.e. strip away add and remove) using .values again
Flatten the entire array recursively so we end up with an array that is one level deep using .flatMapDeep
You might also notice the chain(data) syntax, this is just a way to improve the readability and sometimes performance of your lodash code, so that you don't have to nest each lodash function that you use. Check out the docs on chain for more info.

Categories