ecrmnn / collect.js Goto Github PK
View Code? Open in Web Editor NEW💎 Convenient and dependency free wrapper for working with arrays and objects
Home Page: https://collect.js.org
License: MIT License
💎 Convenient and dependency free wrapper for working with arrays and objects
Home Page: https://collect.js.org
License: MIT License
This is awesome collection as like laravel .
like operator is very important as query system.
.where('name','like','s%')
another is
.orWhere()
.where('votes', '>', 100)
.orWhere('name', 'John')
andWhere()
array condition
$users = DB::table('users')->where([
['status', '=', '1'],
['subscribed', '<>', '1'],
])->get();
without those can't feel happiness .please add those collections. @ecrmnn ❤️
Am i correct in assuming we would include this in the bootstrap.js as follows:
window.collect = require('collect.js')
Thanks!
Would it be possible to auto-cast the collection to an array like Laravel does when PHP expects an array? For example this isn't possible right now:
const collection = collect([1,2,3,4,5]);
for (let item of collection) {
// Do something with item
}
i'm getting this error on firefox
SyntaxError: missing = in const declaration
module.exports = function except(properties) {
const collection = {};
for (const prop in this.items) {
if (properties.indexOf(prop) === -1) {
collection[prop] = this.items[prop];
}
}
return new this.constructor(collection);
};
const collection = collect([{
name: 'JavaScript: The Good Parts', pages: 176
}, {
name: 'JavaScript: The Definitive Guide', pages: 1096
}]);
return collection.only('name').all()
I'm trying to find a 'name' property from the collection. It does not work properly. It displays empty arrays [] I want to know my approach is correct or not.
Thank you.
$collection = new Collection([
['shape' => 'square', 'color' => 'blue', 'val' => 'blue square'],
['shape' => 'square', 'color' => 'blue', 'val' => 'blue square'],
['shape' => 'triangle', 'color' => 'green', 'val' => 'green triangle'],
['shape' => 'triangle', 'color' => 'red', 'val' => 'red triangle'],
]);
$result = $collection->groupBy('shape')->map(
function(Collection $dimension1Group) {
return $dimension1Group->groupBy('color');
}
)->toArray();
//array (
// 'square' =>
// array (
// 'blue' =>
// array (
// 0 =>
// array (
// 'shape' => 'square',
// 'color' => 'blue',
// 'val' => 'blue square',
// ),
// 1 =>
// array (
// 'shape' => 'square',
// 'color' => 'blue',
// 'val' => 'blue square',
// ),
// ),
// ),
// 'triangle' =>
// array (
// 'green' =>
// array (
// 0 =>
// array (
// 'shape' => 'triangle',
// 'color' => 'green',
// 'val' => 'green triangle',
// ),
// ),
// 'red' =>
// array (
// 0 =>
// array (
// 'shape' => 'triangle',
// 'color' => 'red',
// 'val' => 'red triangle',
// ),
// ),
// ),
//)
I'd like to address two things with this example:
The contains function isn't working properly on collections of objects.
Example:
let collection = collect([{
name: 'Steven Gerrard',
number: 8
}, {
name: 'Steve Jobs',
number: 2
}]);
let result = collection.contains('name', 'Steven Gerrard'); // false
// Expected result: true
For people having the same issue, you can currently use the following as a workaround:
collection.where('name', 'Tony Stark').first() === undefined;
hey,
counting objects in a hashmap returns undefined
collect({}).count() // undefined
collect({foo:'bar'}).count() // undefined
might just be a version problem here
Due to the number of implemented functions, the code starts getting a little difficult to parse. Would you be interested in splitting the functions into separate files? It's not necessary, but I feel like it would help encourage contribution.
Great project btw.
`const collection = collect({
a: 'A',
b: 'B',
d: 'D'
});
const merged = collection.merge({
a: 'AAA',
b: 'BBB',
c: 'CCC'
});
console.log(merged.all()) // { a: 'AAA', b: 'BBB', c: 'CCC' } but expect { a: 'AAA', b: 'BBB', c: 'CCC' , d: 'D'}
console.log(merged.all().b) // BBB
merged.forget('b')
console.log(merged.all().b) // B, expect undefined
i know in method file: merge.js and union.js use
var collection = Object.create(this.items), does use
clone` like is right/better?
env: node -v v6.10.2
First thanks for this package, it's like using laravel collections.
I tried to use one of your collections in a v-for in vue and it doesn't iterate over the collection items, instead it iterates over the collection Object properties.
I have the latest version of your package.
Is there a set of typings for use with Angular/TypeScript projects?
Hey,
could you write a short CONTRIBUTING.md, so everyone who wants to constribute knows how.
i myself would like to constribute but i cant get the env working to run those tests.
hey,
i have this pipeline
const stats = collect(this.content)
.filter(value => {
return collect([
'created', 'updated', 'deleted'
]).contains(value.description);
})
.groupBy(value => value.description)
.mapWithKeys(value => {
return [value.description, collect(value.all()).count()];
});
and this does error with this.items.forEach is not a function
at the mapWithKeys
method,
is it intentional that mapWithKeys
does not support hashmaps?
I've opened PR#95 several days ago, which uses reduce
instead of iterator
to implement sum
function with fewer lines of code. However, a simple benchmark test shows iterator_sum
is 3x ~ 5x times faster than reduce_sum
.
According to https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce, reduce
does have extra overhead compared to directly using iterator
.
So the change of PR#95 may be revoked and using origin sum
implementation is better. Using reduce
makes the code shorter, it harms efficiency. How do you think about it? @ecrmnn
The flatMap
method doesn't work as expected for a collection (an array of objects).
For example, if I have a list of employees and each employee has a list of customers and I want to get a list of all customer I would use flatMap as the below:
Input:
let employees = collect([
{
customers :[
{
name : "c1"
},
{
name : "c2"
}
]
},
{
customers :[
{
name : "c3"
}
]
}
])
let customers = employees.flatMap(employee => employee.customers)
Expected result:
[
{
name : "c1"
},
{
name : "c2"
},
{
name : "c3"
}
]
Actual result:
Error: Cannot read property '0' of undefined(in the collect.js flatMap source code)
Laravel's flatMap source code
Is there a good reason why flatMap behaves like that? If it is an issue with this can you, please, implement the correct version for flatMap?
Thank you!
Hey,
I'm noticing an issue with the merge() method. Here's what I'm getting running the example:
const collection = collect({
id: 1,
price: 29
});
const merged = collection.merge({
price: 400,
discount: false
});
console.log(merged.all());
In my console:
So, I don't have a complete understanding of JS prototypes, but from what I can see the object returned only has the content of the merged object (the second object), and it's prototype has the original data (the first object).
Am I not getting something or is this unexpected behavior ?
Thanks !
Personally, I think ESLint rules is necessary and good for other's contribution.
The random method returns a random item from the collection:
Not only that, it shuffles the collection in place:
const a = collect([1, 2, 3, 4, 5])
console.log(a.random()) // 4
console.log(a.all()) // [3, 5, 1, 4, 2]
I humbly suggest it would be more clear to either update the documentation to note that, or to adjust the code to be pure -- a user might not expect their ordered array to be shuffled when asking for a random element.
Hello
Is it possible to use this package without npm?
I was expecting to see a collect.js
or a collect.min.js
in the dist
folder.
hi, ercmnn.
i am just confused, how does this differ from lodash?
How do I use this in a project created with Angular CLI?
const testCollection = collect(["test-1", "test-2", "test-3", "test-4", "test-5"]);
const test1 = testCollection.pull(0);
console.log(test1);
console.log(testCollection.count());
const test2 = testCollection.pull(1);
console.log(test2);
console.log(testCollection.count());
testCollection.push("test-6");
console.log(testCollection.count());
testCollection.push("test-7");
console.log(testCollection.count());
console.log(testCollection.all());
Knows how to order an array with words with special characters like accents?
Javascript has a native method sort that allows sorting ( array.sort() ). Also you can provide your own custom sorting function. Are two ways to overcome this behavior localeCompare and Intl.Collator provided. in .sortBy() could have this option.
collect(array).sortBy('name');
returns 'Albacete' before 'Álava', and I want 'Álava' before 'Albacete'. =(
Thanks a lot, @ecrmnn
Most methods (like "where") only work on array data.
Take this as an example:
let filtered = collect([
{ test: 1 },
{ test: 2 }
]).where('test', 2);
filtered
equals a collection with just the second object.
However the following throws an exception.
let filtered = collect([
{ test: 1 },
{ test: 2 }
]).keyBy('test').where('test', 2);
This is because by calling keyBy()
the underlying array is converted to an object.
I understand this is done, however I also expect methods like where()
are still usable.
Is it an option to convert the items property to an array (if it is an object) in the affected methods to preserve expected behavior?
Beside this keys also need the be preserved, so just converting it to an array is not a complete solution..
Hi i want to use this library in plain javascript like we use Jquery.
this is very good library and i want to use this in my html file.
please guide how to use this.
It does not work and not return an error
Version: 3.0.47
Collect({
key: 'value'
}).filter((row, key) => {
console.log(row, key);
});
Only:
collect([1, 2, 3, 4, 5]).only([2, 3,12]).all();
// => [ 2 ]
is this correct? or should it output [2,3]?
as i understand, only is the inverse of Expect.
union:
collect([1, 2, 3, 4, 5]).union([2, 3, 4,12]).all()
// =>[ 1, 2, 3, 4, 5 ]
union is supposed to merge them all together?
please see:
http://www.essentialsql.com/wp-content/uploads/2014/10/UnionInsersectExcept.jpg
Problem:
except doesn't work on arrays, but intersect does? Is this inconsistent or correct behavior?
const testE = collect([1,2,3,4,5]).except([2,12]).all()
// result is an object: { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5 }
// think i wanted array: [12]
const testI = collect([1, 2, 3, 4, 5]).intersect([1, 2, 3, 9]).all();
// result: [1,2,3]
except returns object, intersect returns array.
in sql world:
http://www.essentialsql.com/wp-content/uploads/2014/10/UnionInsersectExcept.jpg
thanks :-)
Ps. Love this awesome framework ;-)
hey again,
calling
collection.get('missingKey', 0)
gives null
but should return 0
Bug - Yes
Description - when no arguments are passed filter should remove all the falsy values from the collection.
If I use those three methods(.all, toArray, toJSON) on a collection with sub-collections I get the items
property from children in the result.
It shouldn't recursively get the items for each collection?
Why I have sub-collections? Because I want, at some point, to process only the data from children and I don't want to create temporary variables and instantiate a new collection().
I was looking at the few methods that are not implemented, but which are in Laravel, and was wondering if it might be a good idea to implemented them as aliases/wrappers that just call the intended method? This would keep users from having to worry about differences to Laravel, since overall it is expected to be the same (noting that this collection manager is always strict).
No biggie, just here:
const [underThree, underThree]
In light of the pending Laravel 5.5 release, so you have any plans for add dump
and/or dd
commands?
I'm importing collect globally in laravel's default bootstrap.js
file:
window.collect = require('collect.js');
When I run npm run development
everything works fine.
When I run npm run production
I get the following error:
> @ production C:\www\kilt2016
> cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js
95% emitting ERROR Failed to compile with 1 errors7:21:22 PM
error
/js/oa/vue.57617082aa194c799028.js from UglifyJs
Unexpected token: name (index) [./~/collect.js/src/methods/chunk.js:5,0][/js/oa/vue.57617082aa194c799028.js:79,6]
(Laravel version: 5.4.24, Mix Version: 0.12.1)
Anyone any ideas?
I get a const is not initialized
. It points to this function, but I guess it's valid for all. Would it be possible to make it available for IE too?
Collection.prototype.only = function (properties) {
const collection = {};
for (const prop in this.items) {
if (properties.indexOf(prop) !== -1) {
collection[prop] = this.items[prop];
}
}
return new Collection(collection);
};
hey,
to stay inline with laravel\collection we should update the first
method to match the laravel one
https://github.com/laravel/framework/blob/5.5/src/Illuminate/Support/Arr.php#L154-L181
basicly update the function to
first(key|callback, default|callback)
i try to make a PR
Får ikke compilet dersom du definerer en variabel med let. Eksempelet under fungerer så lenge du har kommentert ut alle let variabler.
*Library is missing Value By Index Functionality
ex
myArray = collect([1,4,5,9,9,5,1,1,5,4,1,7,1,0,9,3,7,4,8,9,3,6,3,3]);
val = myArray[3];
it is not returning value .
it should return value 9
Hi
I am using Laravel 5.5;
I have installed using npm
npm install --save collect.js
and added the following on bootstrap.js
window.collect = require('collect.js')
and run
npm run dev
inside my blade blade file i have added
<script>
collect([1, 2, 3]).all();
</script>
But I am getting an error
ReferenceError: collect is not defined
Hey,
if i want to create a macro for global use, like in laravel. I would do something like this:
collect.marco('hello', function(fn) {
console.log('hello');
});
and then use it were ever i need it.
but with the current implementation i get the error:
collect.macro is not a function
Just checking about the "wrapper for working with arrays and objects". Is this implemented yet? It's just when I pass in an object and try and use many of the functions: transform
, map
, pop
etc. then it fails as it is trying to call the corresponding methods on this.items
assuming that it is an array.
Am I doing something wrong or can I just not use objects in collect.js?
Brilliant library otherwise 👍
Suppose there is an object collection like that
people = {
name: 'wei',
sex: 'male',
phone: [15211111111, 13511111111],
company: {
name: 'IBM',
city: 'BJ'
}
}
What does it should be if we call collect(people).toArray()
?
In current implementation, it will return
[ 'wei', 'male', [ 15211111111, 13511111111 ], { name: 'IBM', city: 'BJ' } ]
.
Should it be [ 'wei', 'male', [ 15211111111, 13511111111 ], [ 'IBM', 'BJ' ] ]
?
<template lang="html">
<div class="app">
{{ test}}
</div>
</template>
<script>
import collect from 'collect.js'
export default {
data () {
return {
msg: 'Atom_Vue',
test: ' '
}
},
created() {
this.test = collect([1, 2, 3, 4]).count()
},
}
</script>
<style lang="css" scoped >
</style>
Error in render: "TypeError: [1,2,3,4].count is not a function"
i want something like
const collect = require('collect.js')
collect(['a', 'b', 'c'])
.toArray(array => /** do something */)
it is possible to achieve with current version?
Thanks for your work on this. Do you have any stats on upper limits with larger collection sizes, benchmarked performances etc?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.