print object in a array [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a api with json like this:
{
"data": [
{
"carrier" : "abc",
"extra": {
"date": "1970-01-01"
},
}
{
"carrier" : "abc",
"extra": {
"date": "1970-01-01"
},
}
]
}
Then how can I use date and carrier in a map function.
I am using reactjs

const obj = {
"data": [
{
"carrier" : "abc",
"extra": {
"date": "1970-01-01"
},
}
{
"carrier" : "abc",
"extra": {
"date": "1970-01-01"
},
}
]
}
const newArray = object.data.map(ele => {
return {
carrier: ele.carrier,
date: ele.extra && ele.extra.date
};
})
// Result
[
{ carrier: "abc", date: "1970-01-01" },
{ carrier: "abc", date: "1970-01-01" }
]

const dataObj = {
data: [
{
carrier: "abc",
extra: {
date: "1970-01-01"
}
},
{
carrier: "abc",
extra: {
date: "1970-01-01"
}
}
]
};
const dateArr = dataObj.data.map(obj => {
return {
date : obj.extra?.date,
carrier : obj.carrier,
}
});
dateArr
[
{ carrier: "abc", date: "1970-01-01" },
{ carrier: "abc", date: "1970-01-01" }
]

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)

How to filter from an object by iterating over it in js

I am trying to get the value of "type" from the object by iterating over it. The object looks like this.
{
"team": {
"table": [
{
"cityCode": 123,
"list": {
"players": [
{
"name": "peter",
"school": "x",
"awards": {
"type": "gold"
},
"year": 2019
}
]
}
},
{
"cityCode": 456,
"list": {
"players": [
{
"name": "Dave",
"school": "y",
"awards": {
"type": "silver"
},
"year": 2018
}
]
}
}
]
}
}
I am able to get the type values using this:
const table = team.table;
for (let i = 0; i < table.length; i++) {
const values = {
type: table[i].list.players
.filter((a) => a.awards != null)
.map((a) => a.awards.type)
.join(" "),
};
}
However, I want to use another filter on the "list" to filter non null lists. So how can I achieve that.
You want to check Check if 'list' key exists inside a team.table JSON object
you can check by
if(table[i].hasOwnProperty('list')){
}
code is
const table = team.table;
for (let i = 0; i < table.length; i++) {
if(table[i].hasOwnProperty('list')){
const values = {
type: table[i].list.players
.filter((a) => a.awards != null)
.map((a) => a.awards.type)
.join(" "),
};
}
}
1) You can get all type using flatMap and map as:
obj.team.table.flatMap((o) => o.list.players.map((o) => o.awards.type))
const obj = {
team: {
table: [
{
cityCode: 123,
list: {
players: [
{
name: "peter",
school: "x",
awards: {
type: "gold",
},
year: 2019,
},
],
},
},
{
cityCode: 456,
list: {
players: [
{
name: "Dave",
school: "y",
awards: {
type: "silver",
},
year: 2018,
},
],
},
},
],
},
};
const types = obj.team.table.flatMap((o) => o.list.players.map((o) => o.awards.type));
console.log(types);
2) Using forEach and destructuring as:
const obj = {
team: {
table: [
{
cityCode: 123,
list: {
players: [
{
name: "peter",
school: "x",
awards: {
type: "gold",
},
year: 2019,
},
],
},
},
{
cityCode: 456,
list: {
players: [
{
name: "Dave",
school: "y",
awards: {
type: "silver",
},
year: 2018,
},
],
},
},
],
},
};
const table = obj.team.table;
const types = [];
for (let i = 0; i < table.length; i++) {
const { list: { players } } = table[i]
players.forEach(({ awards: { type }}) => types.push(type))
}
console.log(types);
It will be cleaner to use forEach.
You will need 2 forEach due to your data structure.
But below code will:
check if awards is null
check if awards.type is null
const data = {
"team": {
"table": [
{
"cityCode": 123,
"list": {
"players": [
{
"name": "peter",
"school": "x",
"awards": {
"type": "gold"
},
"year": 2019
}
]
}
},
{
"cityCode": 456,
"list": {
"players": [
{
"name": "Dave",
"school": "y",
"awards": {
"type": "silver"
},
"year": 2018
},
{
"name": "Dave",
"school": "y",
"awards": {
"type": "gold"
},
"year": 2016
}
]
}
},
{
"cityCode": 444,
"list": {
"players": [
{
"name": "James",
"school": "y",
"awards": {
"type": null
},
"year": 2016
}
]
}
},
{
"cityCode": 555,
"list": {
"players": [
{
"name": "Name 101",
"school": "y",
"awards": {
"type": "platinum"
},
"year": 2016
},
{
"name": "Name 102",
"school": "y",
"awards": {
"type": null
},
"year": 2016
},
{
"name": "Name 103",
"school": "y",
"awards": null,
"year": 2016
},
]
}
}
]
}
}
// Expanded your data with more items
const data1 = data.team.table;
let types = []
data1.forEach((item, index) => {
item.list.players.forEach((player) => {
const awards = player.awards;
if (awards !== null && awards.type !== null) {
types = [...types, awards.type];
}
})
})
// Get the list of types
console.log(types);
// Get unique list of types
let unique_types = [...new Set(types)]
console.log(unique_types);

JSON.stringify only key value

I want to compare a object with a string. To do so I JSON.stringify the object(date). How can I extract the value only? I could splice the result but thought about a faster solution. Any other possibilites how to get "10.09.2021" out of {"date":"10.09.2021"}?
var graph = {
"nodes": [
{
"id": 1,
"dates": [
{
"date": "10.09.2021"
},
{
"date": "12.10.2021"
}
]
}, {
"id": 2,
"dates": [
{
"date": "20.09.2021"
},
{
"date": "25.09.2021"
}
]
}, {
"id": 3,
"dates": [
{
"date": "07.10.2021"
},
{
"date": "12.10.2021"
}
]
}
]
}
graph.nodes.forEach(element => {
element.dates.forEach(date => {
strDate = JSON.stringify(date)
console.log(strDate) // {"date":"dd.mm.yyyy"}
//how to extract "dd.mm.yyyy" only?
if (strDate === "12.10.2021") {
console.log("true")
}
})
})
In stringify you just have to access the key of date object recieved in forEach. Please see below code
strDate = JSON.stringify(date.date) or strDate = JSON.stringify(date['date'])
you don't need to use stringify at all. just address it as regular object.
var graph = {
"nodes": [
{
"id": 1,
"dates": [
{
"date": "10.09.2021"
},
{
"date": "12.10.2021"
}
]
}, {
"id": 2,
"dates": [
{
"date": "20.09.2021"
},
{
"date": "25.09.2021"
}
]
}, {
"id": 3,
"dates": [
{
"date": "07.10.2021"
},
{
"date": "12.10.2021"
}
]
}
]
}
graph.nodes.forEach(element => {
element.dates.forEach(date => {
strDate = date.date;
console.log(date.date) // {"date":"dd.mm.yyyy"}
//how to extract "dd.mm.yyyy" only?
if (strDate === "12.10.2021") {
console.log("true")
}
})
})

How to extract all first objects for an object of array? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I make an axios request like that :
async get() {
await this.$axios.get(`my_api_url`)
.then(response => {
this.data = response.data;
}).catch(() => { console.log('error') })
},
It returns a response with these data:
{
"Apple": [
{
"id": 26,
"name": "Apple",
"date_in": "2020-07-01"
},
{
"id": 23,
"name": "Apple",
"date_in": "2020-06-01"
}
],
"Cherry": [
{
"id": 24,
"name": "Cherry",
"date_in": "2020-06-01"
}
],
"Banana": [
{
"id": 25,
"name": "Banana",
"date_in": "2020-06-01"
}
]
}
I would like to be able to browse this object and keep only the first object in each table. Then put the selected objects in a new table.
Is it possible to do this?
function GetObjects(input){
var output = [];
for(let key in input){
output.push(input[key][0]);
}
return output;
}
If I understand your question correctly
Like that?
const src = {"Apple":[{"id":26,"name":"Apple","date_in":"2020-07-01"},{"id":23,"name":"Apple","date_in":"2020-06-01"}],"Cherry":[{"id":24,"name":"Cherry","date_in":"2020-06-01"}],"Banana":[{"id":25,"name":"Banana","date_in":"2020-06-01"}]},
resultArr = Object.values(src).map(([o]) => o)
console.log(resultArr)
.as-console-wrapper{min-height:100%;}
Or, like that?
const src = {"Apple":[{"id":26,"name":"Apple","date_in":"2020-07-01"},{"id":23,"name":"Apple","date_in":"2020-06-01"}],"Cherry":[{"id":24,"name":"Cherry","date_in":"2020-06-01"}],"Banana":[{"id":25,"name":"Banana","date_in":"2020-06-01"}]},
resultObj = Object.entries(src).reduce((r,[key,[o]]) =>
(r[key] = o,r),{})
console.log(resultObj)
.as-console-wrapper{min-height:100%;}
You can get the results like:
const data = {
"Apple": [
{
"id": 26,
"name": "Apple",
"date_in": "2020-07-01"
},
{
"id": 23,
"name": "Apple",
"date_in": "2020-06-01"
}
],
"Cherry": [
{
"id": 24,
"name": "Cherry",
"date_in": "2020-06-01"
}
],
"Banana": [
{
"id": 25,
"name": "Banana",
"date_in": "2020-06-01"
}
]
}
const results = Object.keys(data).filter(item => data[item][0]).map(item => data[item][0]);
console.log(results);

Aggregate data from nested array

I need help with the aggregate framework.
I have a model (currencies field can contain more than one object):
const schema = new mongoose.Schema({
country: { type: String },
code: { type: String },
region: [{
name: { type: String },
path: { type: Array },
city: [{
name: { type: String },
path: { type: Array },
latitude: { type: String },
longitude: { type: String },
}],
}],
currencies: [{
code: { type: String },
name: { type: String },
symbol: { type: String },
}],
})
And I need to receive all currencies without duplicates.
Received data can view like this:
[
{ code: 'string', name: 'sting', symbol: 'string' },
{ code: 'string', name: 'sting', symbol: 'string' },
...
]
// or like this:
[
currencies: [
{ code: 'string', name: 'sting', symbol: 'string' },
{ code: 'string', name: 'sting', symbol: 'string' },
...
]
]
I try to create a query
Geo.aggregate([
{
$group: {
_id: null,
currencies: { $addToSet: '$currencies' },
},
},
])
but receive this data with duplicates and it has many nested arrays:
[
{
"_id": null,
"currencies": [
[
{
"_id": "5cd9486248989616a411fac5",
"code": "JPY",
"name": "Japanese yen",
"symbol": "¥"
}
],
[
{
"_id": "5cd9491a48989616a411fb47",
"code": "TRY",
"name": "Turkish lira",
"symbol": null
}
],
I try this query:
Geo.aggregate([
{
$addFields: {
code: '$currencies.code',
name: '$currencies.name',
symbol: '$currencies.symbol',
},
},
])
But I receive error "TypeError: item is not iterable".
I need little help )
Db data views like this:
{
"_id": {
"$oid": "5c3334a8871695568817eadf"
},
"country": "Singapore",
"code": "sg",
"region": [
{
"path": [
"Singapore"
],
"_id": {
"$oid": "5c3366c63d92ac6e531e05c0"
},
"city": [],
"name": "Central Singapore Community Development Council"
},
....
],
"__v": 0,
"currencies": [
{
"_id": {
"$oid": "5cd948ec48989616a411fb28"
},
"code": "BND",
"name": "Brunei dollar",
"symbol": "$"
},
{
"_id": {
"$oid": "5cd948ec48989616a411fb27"
},
"code": "SGD",
"name": "Singapore dollar",
"symbol": "$"
}
]
}
In aggregate pipeline first you need to unwind the currencies array and then group them by condition to get desired result.
Geo.aggregate([
{
$unwind: '$currencies'
},
{
$group: {
_id: null,
currencies: { $addToSet: '$currencies' },
},
},
])
For more information you can look into documentation here
db.temp.aggregate([
{$project : {currencies : 1}},
{$unwind: "$currencies"},
{
$addFields: {
currencyHash: {
$concat : ['$currencies.code', "--", "$currencies.name", "--", "$currencies.symbol"]
}
}
},
{
$group: {
_id: "$currencyHash",
currency : {
$first : "$currencies"
}
}
},
{
$project: {
code : "$currency.code",
name : "$currency.name",
symbol : "$currency.symbol"
}
},
{
$project: {
_id : 0,
currency : 0
}
}
]).pretty()

Categories

Resources