I'm using below function for building a tree list and is okey with local obj_list object, Why That not work with mongodb doc object?
Code:
const promise = Tree.find({uid: mongoose.Types.ObjectId('5c17974259bf01254c9c7f56')}, {'_id': false, 'uid': false}).exec();
promise.then(async (doc) => {
const obj_list = doc; // not work with doc object in db
const obj_list = [{ // work localy
nid: 1,
name: 'father',
parent: '0',
__v: 0,
},
{
nid: 2,
name: 'boy',
parent: '1',
__v: 0,
}];
console.log(doc);
console.log(obj_list);
const obj_nested_list = [];
let obj;
function fill_with_children(children_arr, parent_id) {
for (let i = 0; i < obj_list.length; i++) {
obj = obj_list[i];
if (obj.parent == parent_id) {
children_arr.push(obj);
obj.children = [];
fill_with_children(obj.children, obj.nid);
}
}
}
fill_with_children(obj_nested_list, 0);
console.log(obj_nested_list);
}).catch((err) => {
if (err) {
console.log(err);
}
});
console.log(doc):
[ { nid: 1, name: 'father', parent: '0', __v: 0 },
{ nid: 2, name: 'boy', parent: '1', __v: 0 } ]
console.log(obj_list):
[ { nid: 1, name: 'father', parent: '0', __v: 0 },
{ nid: 2, name: 'boy', parent: '1', __v: 0 } ]
output with doc: // not ok
[ { nid: 1, name: 'father', parent: '0', __v: 0 } ]
output with obj_list: // ok
[ { nid: 1,
name: 'father',
parent: '0',
__v: 0,
children: [ [Object] ] } ]
Mongoose query promises resolve to a Document object, not a plain JavaScript object. If you want a plain JavaScript object to manipulate and log, you should use Query#lean:
const promise = Tree.find(…).lean().exec();
promise.then(…);
Related
Let say I have two array of objects.
var arr1= [
{
pid: [ '1967', '967' ],
},
{
pid: [ '910', '1967', '967' ],
},
{
pid: [ '967' ],
}
]
var arr2 = [
{ _id: '967', name: 'test pid' },
{ _id: '1967', name: 'test one test' },
{ _id: '910', name: 'this is test name' }
]
is there any way I can find the _id and name from array2 using the id from arr1 and replace element of arr1.pid. like below
arr1 = [
{
pid: [ { _id: '1967', name: 'test one test' }, { _id: '967', name: 'test pid' }],
},
{
pid: [ { _id: '910', name: 'this is test name' }, { _id: '1967', name: 'test one test' }, { _id: '967', name: 'test pid' } ],
},
{
pid: [ { _id: '967', name: 'test pid' } ],
}
]
so far I have done as below
for (var i = 0; i < arr1.length; i++){
var pids = arr1[i].pid
for(var j = 0; j<pids.length; j++){
var result = arr2.filter(obj => {
return obj._id === pids[j]
})
console.log(result) //can not push this into arr1['pid']
}
}
You can map it and inside that you can find the elemenet from second array:
var arr1= [ { pid: [ '1967', '967' ], }, { pid: [ '910', '1967', '967' ], }, { pid: [ '967' ], }];
var arr2 = [ { _id: '967', name: 'test pid' }, { _id: '1967', name: 'test one test' },{ _id: '910', name: 'this is test name' } ];
var result = arr1.map(k=>{
k.pid = k.pid.map(p=>arr2.find(n=>n._id==p));
return k;
});
console.log(result);
Build an object from arr2, so that easy access given key.
Use map on arr1 and update the array.
var arr1 = [
{
pid: ["1967", "967"],
},
{
pid: ["910", "1967", "967"],
},
{
pid: ["967"],
},
];
var arr2 = [
{ _id: "967", name: "test pid" },
{ _id: "1967", name: "test one test" },
{ _id: "910", name: "this is test name" },
];
// Build an object to from array
const all = arr2.reduce(
(acc, curr) => ((acc[curr._id] = { ...curr }), acc),
{}
);
const res = arr1.map(({ pid }) => ({
pid: pid.map((key) => ({ ...all[key] })),
}));
console.log(res);
I have the array as below
test_list = [
{
id: 1,
test_name: 'Test 1',
members: [
{
user_id: 3
},
{
user_id: 4
}
],
},
{
id: 2,
test_name: 'Test 2',
members: [
{
user_id: 4
},
{
user_id: 5
},
],
},
{
id: 3,
test_name: 'Test 2',
members: [
{
user_id: 8
},
{
user_id: 10
},
],
}
]
I want to filter the test for specific user_id, example if user_id = 4 I would like to have this result
{
id: 1,
...
},
{
id: 2,
...
},
I have tried with this but it only return the member
test_list.filter(function(item) {
item.members.filter(function(member) {
if(member.user_id === 4) {
return item;
}
});
})
Would anyone please help me in this case?
Check if .some of the objects in the members array have the user_id you're looking for:
test_list = [{
id: 1,
test_name: 'Test 1',
members: [{
user_id: 3
},
{
user_id: 4
}
],
},
{
id: 2,
test_name: 'Test 2',
members: [{
user_id: 4
},
{
user_id: 5
},
],
},
{
id: 3,
test_name: 'Test 2',
members: [{
user_id: 8
}]
}
];
const filtered = test_list.filter(
({ members }) => members.some(
({ user_id }) => user_id === 4
)
);
console.log(filtered);
You could use .reduce() and .filter() method of array to achieve required result.
Please check below working code snippet:
const arr = [{"id":1,"test_name":"Test 1","members":[{"user_id":3},{"user_id":4}]},{"id":2,"test_name":"Test 2","members":[{"user_id":4},{"user_id":5}]},{"id":3,"test_name":"Test 2","members":[{"user_id":8}]}];
const data = arr.reduce((r,{ members,...rest }) => {
let rec = members.filter(o => o.user_id === 4)
if(rec.length){
rest.members = rec;
r.push(rest);
}
return r;
},[]);
console.log(data);
Hope this works.
var members = item.members;
var filterById =members.filter((item1)=>{
return (item1.user_id===4)
});
return filterById.length > 0;
});
console.log(test_List_by_id)```
I would like to loop through an array of elements and find the index # of the one that matches certain criteria. Take the following array:
services: [
{ _id: <ObjectId>,
name: "initiating"
},
{ _id: <ObjectId>,
name: "evaluating"
},
{ _id: <ObjectId>,
name: "servicing"
},
]
How would I loop through this array and pull out the array index # of the object where the property "name" is equal to "evaluating" (i.e. - array element #1)?
Try Array.prototype.findIndex:
const services = [
{ _id: 1,
name: "initiating"
},
{ _id: 2,
name: "evaluating"
},
{ _id: 3,
name: "servicing"
},
];
console.log(
services.findIndex(({ name }) => name === 'evaluating')
);
let services = [{
_id: 0,
name: "initiating"
},
{
_id: 1,
name: "evaluating"
},
{
_id: 2,
name: "servicing"
},
];
let index = services.findIndex(item => item.name === "evaluating");
document.write(index);
This will return the index after searching through the each object's name property and comparing it to "evaluating".
let services = [{
_id: 0,
name: "initiating"
},
{
_id: 1,
name: "evaluating"
},
{
_id: 2,
name: "servicing"
},
]
let selected = services.findIndex(service => service.name == "evaluating")
console.log(selected)
You may use .reduce():
var services = [
{
_id: '<ObjectId>',
name: "initiating"
},
{
_id: '<ObjectId>',
name: "evaluating"
},
{
_id: '<ObjectId>',
name: "servicing"
},
];
var idx = services.reduce((x, ele, idx) => (ele.name=='evaluating') ? idx : x, -1);
console.log(idx);
I have an array of json objects. First object always has empty data, the second and other items always have the same structure.
How can I return one array item (1 object) that contains particular document field (x.data.outputs.document)?
var x = [
{
timestamp: 3455435654345,
hash: "f78ed219d5b60a3665e7382f",
data: [],
nonce: 0,
difficulty: 2
},
{
timestamp: 1528020475945,
hash: "01a3c43290652bc8f858651dc5",
data: [
{
id: "fc453bd0-6715-11e8-b7d9-1156bded578e",
input: {
timestamp: 1528020475917,
address:
"0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4dcQ3P5fs",
signature:
"af43a84e5e0e59b9af713cc5e99ce768b318e5"
},
outputs: [
{
document: "a8ab1940bf8a7e13fe8e805470756a28",
address:
"IGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC"
}
]
}
],
nonce: 2,
difficulty: 1
},
{
timestamp: 1528020491868,
hash: "fb47a96d8a3bce4d81fe88122d60266a",
data: [
{
id: "05c5ca30-6716-11e8-b7d9-1156bded578e",
input: {
timestamp: 1528020491859,
address:
"A0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4dcQ3P5",
signature:
"152d22b6328bea1c4815bad8d639248bb11a"
},
outputs: [
{
document: "5cbe7e76bc24d54e71bcb45daa793a3c",
address:
"Q3P5fsOZMemlIRiXx5Qfo7\nGCaa7eNu82Cl"
}
]
}
],
nonce: 1,
difficulty: 2
}
];
I've tried this:
x.find(
item =>
item.data.outputs.document == "a8ab1940bf8a7e13fe8e805470756a28"
)
TypeError: Cannot read property 'document' of undefined
And this (the same error):
var newArray = str.filter(function(el) {
return el.data.outputs.document == "5cbe7e76bc24d54e71bcb45daa793a3c";
});
Is it possible to access document field and find object with some document value ?
You can guard access to nested properties using syntax such as obj && obj.prop1 && obj.prop1.prop2 etc.
var data = [{
timestamp: 3455435654345,
hash: "f78ed219d5b60a3665e7382f",
data: [],
nonce: 0,
difficulty: 2
}, {
timestamp: 1528020475945,
hash: "01a3c43290652bc8f858651dc5",
data: [{
id: "fc453bd0-6715-11e8-b7d9-1156bded578e",
input: {
timestamp: 1528020475917,
address: "0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4dcQ3P5fs",
signature: "af43a84e5e0e59b9af713cc5e99ce768b318e5"
},
outputs: [{
document: "a8ab1940bf8a7e13fe8e805470756a28",
address: "IGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC"
}]
}],
nonce: 2,
difficulty: 1
}, {
timestamp: 1528020491868,
hash: "fb47a96d8a3bce4d81fe88122d60266a",
data: [{
id: "05c5ca30-6716-11e8-b7d9-1156bded578e",
input: {
timestamp: 1528020491859,
address: "A0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4dcQ3P5",
signature: "152d22b6328bea1c4815bad8d639248bb11a"
},
outputs: [{
document: "5cbe7e76bc24d54e71bcb45daa793a3c",
address: "Q3P5fsOZMemlIRiXx5Qfo7\nGCaa7eNu82Cl"
}]
}],
nonce: 1,
difficulty: 2
}];
function findObjectsWithAddress(address) {
return data.filter(
a =>
a.data &&
a.data.find(
b =>
b.outputs &&
b.outputs.find(c => c.address == address)
)
)
}
function extractAddresses() {
var addresses = []
for (let a of data) {
if (!a.data) {
continue;
}
for (let b of a.data) {
if (!b.outputs) {
continue;
}
for (let c of b.outputs) {
if ('address' in c) {
addresses.push(c.address)
}
}
}
}
return addresses
}
console.log(findObjectsWithAddress('IGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC'))
console.log(extractAddresses())
data and outputs are arrays, you need to access it with the proper index before accessing its children, like: el.data[0].outputs[0].document. In your case you are searching for a specific value, so it should be:
var x = [
{
timestamp: 3455435654345,
hash: "f78ed219d5b60a3665e7382f",
data: [],
nonce: 0,
difficulty: 2
},
{
timestamp: 1528020475945,
hash: "01a3c43290652bc8f858651dc5",
data: [
{
id: "fc453bd0-6715-11e8-b7d9-1156bded578e",
input: {
timestamp: 1528020475917,
address:
"0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4dcQ3P5fs",
signature:
"af43a84e5e0e59b9af713cc5e99ce768b318e5"
},
outputs: [
{
document: "a8ab1940bf8a7e13fe8e805470756a28",
address:
"IGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC"
}
]
}
],
nonce: 2,
difficulty: 1
},
{
timestamp: 1528020491868,
hash: "fb47a96d8a3bce4d81fe88122d60266a",
data: [
{
id: "05c5ca30-6716-11e8-b7d9-1156bded578e",
input: {
timestamp: 1528020491859,
address:
"A0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4dcQ3P5",
signature:
"152d22b6328bea1c4815bad8d639248bb11a"
},
outputs: [
{
document: "5cbe7e76bc24d54e71bcb45daa793a3c",
address:
"Q3P5fsOZMemlIRiXx5Qfo7\nGCaa7eNu82Cl"
}
]
}
],
nonce: 1,
difficulty: 2
}
];
outer: for(let item of x) {
for(let data of item.data) {
let match = data.outputs.find(o => o.document === "a8ab1940bf8a7e13fe8e805470756a28");
if(match) {
console.log(match);
break outer;
}
}
}
I've got follow code:
list1 = {
Items: [
{
ID: 1,
Name: "Zurich"
},
{
ID: 2,
Name: "London"
}, {
ID: 3,
Name: "New York"
}
]
};
list2 = {
Items: [
{
ID: -1,
Name: "Dummy"
},
{
ID: 0,
Name: "Dummy2"
}
]
};
list1.push(list2);
I expect follow result:
list1:
0: Object (Zurich)
1: Object (London)
3: Object (New York)
4: Object (Dummy)
5: Object (Dummy2)
But I get this one:
list1:
0: Object (Zurich)
1: Object (London)
2: Object (New York)
3: Object (Items)
0: Object (Dummy)
1: Object (Dummy2)
How can I get my expectet result?
Thanks and cheers.
Beside Array#concat, you could use Array#push.apply for it
var list1 = { Items: [{ ID: 1, Name: "Zurich" }, { ID: 2, Name: "London" }, { ID: 3, Name: "New York" }] },
list2 = { Items: [{ ID: -1, Name: "Dummy" }, { ID: 0, Name: "Dummy2" }] };
[].push.apply(list1.Items, list2.Items);
console.log(list1);
The question was how to do this with push() not concat():
for (var i = 0; i < list2.Items.length; i++) {
list1.Items.push(list2.Items[i]);
}
Use the spread operator:
list1.Items.push(...list2.Items)
Spread is an ES2015 feature. Your target browsers or runtime may not support it yet, so check the compatibility table (or use a transpiler like babel).
list1 = {
Items: [
{
ID: 1,
Name: "Zurich"
},
{
ID: 2,
Name: "London"
}, {
ID: 3,
Name: "New York"
}
]
};
list2 = {
Items: [
{
ID: -1,
Name: "Dummy"
},
{
ID: 0,
Name: "Dummy2"
}
]
};
list1.Items = list1.Items.concat(list2.Items);
console.log(list1);
try with:
list2.items.forEach(function (item) {
list1.items.push(item)
})
You need to loop through each items in list2 and then fetch them to push into list1.. Below is the snippet using $.each
var list1 = {
Items: [
{
ID: 1,
Name: "Zurich"
},
{
ID: 2,
Name: "London"
}, {
ID: 3,
Name: "New York"
}
]
};
var list2 = {
Items: [
{
ID: -1,
Name: "Dummy"
},
{
ID: 0,
Name: "Dummy2"
}
]
};
$(list2.Items).each(function(k,v){
list1.Items.push(v);
})
console.log(list1);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>