gpt4 book ai didi

javascript - 从 javascript litteral 获取第一个对象

转载 作者:行者123 更新时间:2023-11-28 12:37:50 25 4
gpt4 key购买 nike

假设我这里有这个对象:

var items = [
{name:"Foo"},
{name:"Bar"},
{name:"foo"},
{name:"bar"},
{name:"foobar"},
{name:"barfoo"}
];

由于每个对象中只有一个项目,因此我只想返回它们的列表。

我尝试过这个:

var getSingle = function(rows){
var items = [];
//This should only return one column
for (var i = 0; i < rows.length; i++) {
var r = rows[i];
var c = 0;
for (var n in r) {
if(c == 0)
items.push(r[n]);
c += 1;
}
}
return items;
}

但是好像不行。有什么想法吗?

PS。 name 可以是任何东西。

最佳答案

我使用了与其他人不同的方法,因为我做了两个假设:

1/你不知道键的名称,但每个项目只有一个键2/每个项目的 key 可以不同我会给你第二个选择,第二个假设是:2/所有项目只有一个 key ,但对所有项目来说都是相同的

第一个选项:

var items = [
{name:"Foo"},
{name:"Bar"},
{name:"foo"},
{name:"bar"},
{name:"foobar"},
{name:"barfoo"}
];

// object keys very simple shim
Object.keys = Object.keys || function(o) {
var result = [];
for(var name in o) {
if (o.hasOwnProperty(name))
result.push(name);
}
return result;
};

// function to get the value of every first keys in an object
// just remember that saying "first key" does not make real sense
// but we begin with the assumption that there IS ONLY ONE KEY FOR EVERY ITEM
// and this key is unknown
function getFirstKeysValues(items) {
var i = 0, len = items.length, item = null, key = null, res = [];
for(i = 0; i < len; i++) {
item = items[i];
key = Object.keys(item).shift();
res.push(item[key]);
}

return res;
}

console.log(getFirstKeysValues(items)); //["Foo", "Bar", "foo", "bar", "foobar", "barfoo"]

第二个选项将使用 map ,因为我们相信每个 child 都拥有相同的 key (我不会使用这个,因为我不太喜欢 .map - 兼容性):

var items = [
{name:"Foo"},
{name:"Bar"},
{name:"foo"},
{name:"bar"},
{name:"foobar"},
{name:"barfoo"}
];

// object keys very simple shim
Object.keys = Object.keys || function(o) {
var result = [];
for(var name in o) {
if (o.hasOwnProperty(name))
result.push(name);
}
return result;
};

// function to get the value of every first keys in an object
// just remember that saying "first key" does not make real sense
// but we begin with the asumption that there IS ONLY ONE KEY FOR EVERY ITEM
// and this key is unknown but the same for every child
function getFirstKeysValues(items) {
var key = items.length > 0 ? Object.keys(items[0]).shift() : null;

items = items.map(function (item) {
return item[key];
});

return items;
}

console.log(getFirstKeysValues(items));

关于javascript - 从 javascript litteral 获取第一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15286159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com