Console log the value of item in array - javascript

I have this array and I want to console log item value. How can I do that? I got this array from MongoDB. I would appreciate any help.
{
"_id" : "61462a7bf3c0be993bcfdc3e",
"item": "journal",
"qty": 25,
"size": {
"h": 14,
"w": 21,
"uom": "cm"
},
"status": "A"
}
Edit:
I looked in MongoDB documentation and found the solution. Thanks to everyone who answered.

I think you can simply access the key from the object like this:
const obj = {
"_id" : "61462a7bf3c0be993bcfdc3e",
"item": "journal",
"qty": 25,
"size": {
"h": 14,
"w": 21,
"uom": "cm"
},
"status": "A"
}
console.log(obj.item);
Another way could be to find out the keys and iterate over them if keys are dynamic in nature:
const obj = {
"_id" : "61462a7bf3c0be993bcfdc3e",
"item": "journal",
"qty": 25,
"size": {
"h": 14,
"w": 21,
"uom": "cm"
},
"status": "A"
}
const keys = Object.keys(obj);
keys.forEach(key => console.log(`Key is ${key} and the value is ${JSON.stringify(obj[key])}`))

You can try:
Object.entries(YOUR_OBJECT_NAME).filter(val=>val[0] === "item")
You will get back an array of key and value pair. You can then console.log your value.
Easier solution is that you directly determine your key. If you know what is the name of your key then you can do:
console.log(YOUR_OBJECT_NAME.item)

Related

Remove the first bracket from nested array

I have an array as follow:
let data =[
[
{
"Id": "110d611c-54e4-4593-a835-def0f34ed882",
"duration": 30,
"name": "burger",
"price": 10,
}
],
[
{
"Id": "edc241e9-5caf-4f0b-b6ea-6cf5fc57d260",
"duration": 10,
"name": "Cake",
"price": 5,
}
]
]
I am trying to remove the first bracket to be like this:
let data =
[
{
"Id": "110d611c-54e4-4593-a835-def0f34ed882",
"duration": 30,
"name": "burger",
"price": 10,
}
],
[
{
"Id": "edc241e9-5caf-4f0b-b6ea-6cf5fc57d260",
"duration": 10,
"name": "Cake",
"price": 5,
}
]
I have trying many solutions, the most common one i have tried is using this way:
let newData = data[0]
but the result always giving me the first nested array something like this:
[
{
"Id": "110d611c-54e4-4593-a835-def0f34ed882",
"duration": 30,
"name": "burger",
"price": 10
}
]
I tried to convert it to string using JSON.stringify() then remove the bracket by doing
JSON.stringify(data).substring(1, JSON.stringify(data).length - 1);
But then when i parse it i get this error:
SyntaxError: JSON Parse error: Unable to parse JSON string
I am really stuck on what the best way to accomplish it.
thanks in advance.
You want the first element of each nested array, not the first element of the outer array. So use map().
let data = [
[{
"Id": "110d611c-54e4-4593-a835-def0f34ed882",
"duration": 30,
"name": "burger",
"price": 10,
}],
[{
"Id": "edc241e9-5caf-4f0b-b6ea-6cf5fc57d260",
"duration": 10,
"name": "Cake",
"price": 5,
}]
];
let newData = data.map(el => el[0]);
console.log(newData);
Removing the external bracket will result in an invalid javascript object.
To obtain a single array with all the objects you can use flatMap
data.flatMap(x => x)
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap
The result that you want is not valid, instead you can get array of object using flat as:
data.flat()
let data = [
[
{
Id: "110d611c-54e4-4593-a835-def0f34ed882",
duration: 30,
name: "burger",
price: 10,
},
],
[
{
Id: "edc241e9-5caf-4f0b-b6ea-6cf5fc57d260",
duration: 10,
name: "Cake",
price: 5,
},
],
];
const result = data.flat();
console.log(result);

Filter nested arrays using .filter() function

I have an array that looks like this:
const data = [
{"total": 24,"items":[{"id":1,"name":"foo1", "items": [{"label": "TEST", "total": 50}, {"label": "TEST2", "total": 50}]}]},
{"total": 25,"items":[{"id":2,"name":"foo2", "items": [{"label": "FOO", "total": 60}, {"label": "ANOTHER2", "total": 50}]}]},
{"total": 26,"items":[{"id":3,"name":"foo3", "items": [{"label": "BAR", "total": 70}, {"label": "LAST2", "total": 50}]}]},
];
and I wanted to use the .filter() function in angular so when I pass in the string '2', it returns the object containing only the nested arrays which contains the string '2', in other words should return this:
[
{"total": 24,"items":[{"id":1,"name":"foo1", "items": [{"label": "TEST2", "total": 50}]}]},
{"total": 25,"items":[{"id":2,"name":"foo2", "items": [{"label": "ANOTHER2", "total": 50}]}]},
{"total": 26,"items":[{"id":3,"name":"foo3", "items": [{"label": "LAST2", "total": 50}]}]},
];
I tried
let values = data.items.filter(d => d.items.forEach(c => c.label.toLowerCase().includes(searchText.toLowerCase())
}))
and it just returns an empty array,
I also tried
let values = data.items.forEach(d => d.items.filter(c => c.label.toLowerCase().includes(searchText.toLowerCase())
}))
and
let values = data.items.filter(d => d.items.every(c => c.label.toLowerCase().includes(searchText.toLowerCase())
}))
and both return undefined and an empty array.
what is the correct way to do this?
const data = [
{"total": 24,"items":[{"id":1,"name":"foo1", "items": [{"label": "TEST", "total": 50}, {"label": "TEST2", "total": 50}]}]},
{"total": 25,"items":[{"id":2,"name":"foo2", "items": [{"label": "FOO", "total": 60}, {"label": "ANOTHER2", "total": 50}]}]},
{"total": 26,"items":[{"id":3,"name":"foo3", "items": [{"label": "BAR", "total": 70}, {"label": "LAST2", "total": 50}]}]},
];
let searchText='TEST'
let values = JSON.parse(JSON.stringify(data)).map(d => {
d.items.map(i=> {
i.items = i.items.filter(c =>c.label.toLowerCase().includes(searchText.toLowerCase()));
return i;
})
return d;
})
console.log(values)
let values = JSON.parse(JSON.stringify(data)).map(d => {
d.items.map(i=> {
i.items = i.items.filter(c =>c.label.toLowerCase().includes(searchText.toLowerCase()));
return i;
})
return d;
})
forEach doesn't return anything, map returns the array, where each element is replaced by the return value of from the function you pass to it.Also you weren't accessing deep enough, since your target array is at data[0].items[0].items, for example. I might have missed a parenthesis or bracket here

Object version of mapping

Duplicate of: map function for objects (instead of arrays)
How do i map or iterate through an object where the values is another object as such:
[{
"id":2,
"name":"Jane Smith",
"position":"Cook",
"applied":"02/08/16",
"experience":4,
"availability":{
"M":1,
"T":1,
"W":1,
"Th":1,
"F":0,
"S":0,
"Su":0
},
"questions": [{
"text":"Have you ever been convicted of a felony?",
"answer":"Yes"
}]
},
...(2 other objects with the same format)....
]
I need to access the availability object
Beware that there is no guarantee of the order of an object's keys, so there is no perfectly consistent way to iterate over them. However, you can use the for...in statement to iterate over the enumerable properties of an object. You can use that to basically iterate through they key/value pairs of an objects and do something with them.
const availability = {
"M":1,
"T":1,
"W":1,
"Th":1,
"F":0,
"S":0,
"Su":0
};
for (const key in availability) {
console.log(key, availability[key]);
}
// Output:
/*
M 1
T 1
W 1
Th 1
F 0
S 0
Su 0
*/
Since it is unclear exactly how you want to use the data I can't provide any more detail than that but it should get you started.
The map() equivalent of object is Object.keys() and Object.entries()
It is a feature introduced in ES7
const data = [{
"id":2,
"name":"Jane Smith",
"position":"Cook",
"applied":"02/08/16",
"experience":4,
"availability":{
"M":1,
"T":1,
"W":1,
"Th":1,
"F":0,
"S":0,
"Su":0
},
"questions": [{
"text":"Have you ever been convicted of a felony?",
"answer":"Yes"
}]
}
]
console.log(Object.entries(data[0].availability));
console.log(Object.keys(data[0].availability));
Check this here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
For your data if you have more than one object then you can first iterate through the array first using array.map() and use Object.entries() inside map()
I assume you want a list of availability objects.
const availabilityObjects = objects.map(object => object.availability)
Will do it. Code snippet follows:
const objects = [{
"id": 2,
"name": "Jane Smith",
"position": "Cook",
"applied": "02/08/16",
"experience": 4,
"availability": {
"M": 1,
"T": 1,
"W": 1,
"Th": 1,
"F": 0,
"S": 0,
"Su": 0
},
"questions": [{
"text": "Have you ever been convicted of a felony?",
"answer": "Yes"
}]
},
{
"id": 2,
"name": "Jane Smith",
"position": "Cook",
"applied": "02/08/16",
"experience": 4,
"availability": {
"M": 1,
"T": 1,
"W": 1,
"Th": 1,
"F": 0,
"S": 0,
"Su": 0
},
"questions": [{
"text": "Have you ever been convicted of a felony?",
"answer": "Yes"
}]
},
{
"id": 2,
"name": "Jane Smith",
"position": "Cook",
"applied": "02/08/16",
"experience": 4,
"availability": {
"M": 1,
"T": 1,
"W": 1,
"Th": 1,
"F": 0,
"S": 0,
"Su": 0
},
"questions": [{
"text": "Have you ever been convicted of a felony?",
"answer": "Yes"
}]
}
]
console.log(objects.map(object => object.availability))

convert an array of objects to one object of objects

How to convert an array of objects to one object of objects. My function works but I don't want key name before each object.
myArray = [{
"name": "ann",
"y": 191,
"color": "red"
},{
"name": "mary",
"y": 11,
"color": "red"
},{
"name": "henry",
"y": 11,
"color": "red"
}]
let result = {};
for (let item of seriesTotal) {
result[item.name] = item;
delete item.name;
}
I'd like this
myObject = {{
"name": "ann",
"y": 191,
"color": "red"
},{
"name": "mary",
"y": 11,
"color": "red"
},{
"name": "henry",
"y": 11,
"color": "red"
}{
An object is a collection of properties, and a property is an association between a name (or key) and a value.
You can use the index as the key or property name. Use Object.assign to create a new object. Use map and spread syntax to loop thru the array.
let myArray = [{
"name": "ann",
"y": 191,
"color": "red"
}, {
"name": "mary",
"y": 11,
"color": "red"
}, {
"name": "henry",
"y": 11,
"color": "red"
}];
let result = Object.assign(...myArray.map((o,i) => ({[i]: o})));
console.log(result);
Doc: Objects
Since what you want is not valid JS object, you'll get an string in JS, so you could use .replace():
myArray = JSON.stringify(myArray).replace(/(\[)(.+)(\])/g,"{$2}");
console.log(myArray);
//{{"name":"ann","y":191,"color":"red"},{"name":"mary","y":11,"color":"red"},{"name":"henry","y":11,"color":"red"}}
But as I said before, that is not a JS object, it's just a string.

JSON remove key value for particular key name

I have a JSON like the following, I am trying to remove "age" from it and rename "name" to "key" and "height" to "value". Can someone please suggest what would be the neatest way to achieve this.
{
"data": [
{
"name": "A",
"age": 8,
"height": 120
},
{
"name": "B",
"age": 18,
"height": 150
}
]
}
Here is how you do it using map as I mentioned.
map is exactly what you're looking for, it's a way to create a new array based on an existing array using whatever criteria you want.
var json = {
"data": [{
"name": "A",
"age": 8,
"height": 120
}, {
"name": "B",
"age": 18,
"height": 150
}]
};
json.data = json.data.map(function (d) {
return {
key: d.name,
value: d.height
};
});

Categories

Resources