admin管理员组文章数量:1305031
Similar to Array slice(), is it possible to slice an object (without looping though it properties)?
Simplified example:
var obj = {a:"one", b:"two", c:"three", d:"four"};
For example: Get the first 2 properties
var newObj = {a:"one", b:"two"};
Similar to Array slice(), is it possible to slice an object (without looping though it properties)?
Simplified example:
var obj = {a:"one", b:"two", c:"three", d:"four"};
For example: Get the first 2 properties
var newObj = {a:"one", b:"two"};
Share
Improve this question
edited Mar 2, 2015 at 12:14
erosman
asked Mar 2, 2015 at 10:40
erosmanerosman
7,7717 gold badges33 silver badges57 bronze badges
4
-
1
Object.key
turn it into an array ... – Neta Meta Commented Mar 2, 2015 at 10:41 - Object.keys – Hacketo Commented Mar 2, 2015 at 10:41
- 10 How would you define 'first' two properties? Javascript objects' properties do not have any inherent order. stackoverflow./questions/5525795/… – Jozef Legény Commented Mar 2, 2015 at 10:41
- I vote to close this because this is already correctly answered in@JozefLegény ment and in the already posted answer. – F. Hauri - Give Up GitHub Commented Mar 2, 2015 at 10:57
4 Answers
Reset to default 4Technically objects behave like hash tables. Therefore, there is no constant entry order and the first two entries are not constantly the same. So, this is not possible, especially not without iterating over the object's entries.
All major browsers (tested in Firefox 36, Chrome 40, Opera 27) preserve the key order in objects although this is not a given in the standard as Jozef Legény noted in the ments:
> Object.keys({a: 1, b: 2})
["a", "b"]
> Object.keys({b: 2, a: 1})
["b", "a"]
So theoretically you can slice objects using a loop:
function objSlice(obj, lastExclusive) {
var filteredKeys = Object.keys(obj).slice(0, lastExclusive);
var newObj = {};
filteredKeys.forEach(function(key){
newObj[key] = obj[key];
});
return newObj;
}
var newObj = objSlice(obj, 2);
Or for example with underscore's omit
function:
var newObj = _.omit(obj, Object.keys(obj).slice(2));
you can use var newObj = Object.entries(obj).slice(0, 1)
var obj = {a:"one", b:"two", c:"three", d:"four"};
delete obj['d'];
console.info(obj)
/*
sorry i forgot to put quote around d property name
o/p
[object Object] {
a: "one",
b: "two",
c: "three"
}
*/
本文标签: javascriptIs it possible to slice an objectStack Overflow
版权声明:本文标题:javascript - Is it possible to slice an object? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741775672a2397009.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论