Javascript 在Javascript中基本上做`where`子句的最佳方式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6959530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:58:15  来源:igfitidea点击:

Best way of basically doing a `where` clause in Javascript?

javascriptarraysjson

提问by Earlz

I'm trying to parse some JSON that is sent to me and it's all in the format of

我正在尝试解析一些发送给我的 JSON,它的格式为

[{key:value},{key2:value2}, ... ]

What would be the best way to get the value of key2in this? Is there a way to do it without doing a for loop?

获得价值的最佳方式是key2什么?有没有办法在不做 for 循环的情况下做到这一点?

采纳答案by Paul Phillips

You could use the Selectfunction from the Underscore.jslibrary.

您可以使用Underscore.js库中的Select函数。

回答by laurent

Not really, but it wouldn't be hard to create a function to do that. However, it would indeed involves a forloop.

不是真的,但创建一个函数来做到这一点并不难。但是,它确实会涉及一个for循环。

For the sake of completion, that would be the function:

为了完成起见,这将是函数:

function selectWhere(data, propertyName) {
    for (var i = 0; i < data.length; i++) {
        if (data[i][propertyName] !== null) return data[i][propertyName];
    }
    return null;
}

Usage:

用法:

var key2value = selectWhere(data, "key2");

回答by DivineOps

jQuery grep() is a good analog for a Where clause:

jQuery grep() 是 Where 子句的一个很好的模拟:

var array = [{key:1},{key:2}, {key:3}, {key:4}, {key:5}];

var filtered = jQuery.grep(array, function( item, index ) {
  return ( item.key !== 4 && index > 1 );
});

Your filtered array will then contain two elements,

您过滤后的数组将包含两个元素,

 [{key:3}, {key:5}]

回答by Sanghyun Lee

You can't do it with an array, but you can make an associative array like object with it. Once you make it, you can use it like hash.

你不能用数组来做,但你可以用它创建一个像对象这样的关联数组。一旦你成功了,你就可以像哈希一样使用它。

var arr = [{key:value},{key2:value2}, ... ], obj = {};

for (var i = 0, len = arr.length; i < len; i++) {
    $.extend(obj, arr[i]);
}

console.log(obj.key2); // value2

回答by vol7ron

Here's an example that prototype's the Array object. Note:this is shown for example - findis not a good name for this function, and this probably will not be needed for all arrays

这是原型为 Array 对象的示例。 注意:这例如显示 -find不是此函数的好名称,并且可能并非所有数组都需要它

Instead, consider just using the function definition and creating a function like getObjVal, calling like getObjVal(arr,'propName'), similar to LaurenT's answer.

相反,考虑只使用函数定义并创建一个函数 like getObjVal,调用 like getObjVal(arr,'propName'),类似于 LaurenT 的答案。

Given

给定的



var arr = [{key:'value'},{key2:'value2'}];

Definition

定义



// for-loop example
Array.prototype.find = function (prop){
                          for(var i=this.length; i--; )
                             if (typeof this[i][prop] !== 'undefined')
                                return this[i][prop];
                          return undefined;
                       }

// for-each loop example
Array.prototype.find = function (prop){
                          for (var i in this)
                             if ( this.hasOwnProperty(i) && typeof this[i][prop] !== "undefined" ) 
                                return this[i][prop];
                          return undefined;
                       }

Usage

用法



console.log( arr.find('key2') );  // 'value2'
console.log( arr.find('key3') );  // undefined

回答by Dan K

Javascript Array comes with methods that do just what you are asking for - find entries without you having to code a for-loop.

Javascript Array 附带的方法可以满足您的要求 - 无需编写 for 循环即可查找条目。

You provide them with the condition that you want. A compact and convenient way to do that is with an arrow (or "lambda") function. In your case, you are looking for array entries that have a specific key, so the arrow function could look something like this:

你为他们提供你想要的条件。一种紧凑而方便的方法是使用箭头(或“lambda”)函数。在您的情况下,您正在寻找具有特定键的数组条目,因此箭头函数可能如下所示:

e => e.hasOwnProperty("key2")


Following the lead of some of the others, let's start with the assumption

在其他人的带领下,让我们从假设开始

var arr = [{key:"value"}, {key2:"value2"}, {key3:"value3"}]


If you expect that at most one member of the array has the key you want, you can use the find()function. It will test each array member until it finds one where your condition is true, and return it. If none are true, you'll get undefined.

如果您希望数组中最多有一个成员拥有您想要的键,则可以使用该find()函数。它将测试每个数组成员,直到找到一个条件为真的成员,然后返回它。如果都不是真的,你会得到undefined.

var foundentry = arr.find(e => e.hasOwnProperty("key2"))

Either foundentrywill be undefinedor it will be the {key2:"value2"}that you are looking for, and can extract value2from it.

要么foundentryundefined或将成为{key2:"value2"}你所寻找的,并可以提取value2从它。



If arrcan have more than one entry with the key that you are looking for, then instead of find()use filter(). It gives back an array of entries that meet your criteria.

如果arr您要查找的密钥可以有多个条目,则不要find()使用filter(). 它返回一组符合您的条件的条目。

var foundarray = arr.filter(e => e.hasOwnProperty("key2"))

回答by Brian

Regex - no for loop:

正则表达式 - 没有 for 循环:

var key2Val = jsonString.match(/\{key2:[^\}]+(?=\})/)[0].substring("{key2:".length);

回答by Ryan Weiss

Heyas. You can use the lodash library's .reduce()or .transform()functions to implement this. Lodash is more modular than underscore (Underscore around 5kb, Lodash around 17kb), but is generally lighter because you only include the specific modules you need (please see: https://news.ycombinator.com/item?id=9078590for discussion). For this demonstration I will import the entire module (generally not an issue on the backend): I wrote these snippets for either scenario which handle both numeric and non-numeric arguments.

嘿嘿。您可以使用 lodash 库的 .reduce ().transform()函数来实现这一点。Lodash 比 underscore 更模块化(Underscore 大约 5kb,Lodash 大约 17kb),但通常更轻,因为你只包含你需要的特定模块(请参阅:https://news.ycombinator.com/item?id=9078590讨论)。对于这个演示,我将导入整个模块(通常不是后端的问题):我为处理数字和非数字参数的任一场景编写了这些片段。

https://lodash.com/docs#reduce

https://lodash.com/docs#reduce

https://lodash.com/docs#transform

https://lodash.com/docs#transform

Pull in lodash:

拉入 lodash:

var _ = require('lodash');

_.reduce() to where clause:

_.reduce() 到 where 子句:

var delim = ' WHERE ', where = _.isEmpty(options) ? '' : _.reduce(options, function(r, v, k) {
    var w = r + delim + k + '=' + (_.isNumber(v) ? v : ("'" + v + "'"));
    delim = ' AND ';
    return w;
}, '');

_.transform() to where clause:

_.transform() 到 where 子句:

var where = _.isEmpty(options) ? '' : ' WHERE ', delim = '';
_.transform(options, function(r, v, k) {
        where = where + delim + k + '=' + (_.isNumber(v) ? v : ("'" + v + "'"));
        delim = ' AND ';
    });

Hope that helps.

希望有帮助。

回答by Quy

Top answer does the job. Here's a one liner version of it using lodash (same as underscore for the most part):

最佳答案可以完成工作。这是使用 lodash 的单行版本(大部分与下划线相同):

var result = _.filter(data, _.partialRight(_.has, 'key2'));

In lodash, select is just an alias for filter. I pass it the data array filled with objects. I use _.hasas the the filter function since it does exactly what we want: check if a property exists.

在 lodash 中,select 只是过滤器的别名。我将填充了对象的数据数组传递给它。我_.has用作过滤器函数,因为它完全符合我们的要求:检查属性是否存在。

_.hasexpects two args:

_.has期望两个参数:

_.has(object, path)

Since _.hasexpects two arguments, and I know one of them is always constant (the path argument). I use the _.partialRightfunction to append the constant key2. _.partialRightreturns a new function that expects one argument: the object to inspect. The new function checks if obj.key2exists.

由于_.has需要两个参数,我知道其中一个始终是常量(路径参数)。我使用该_.partialRight函数来附加常量key2_.partialRight返回一个需要一个参数的新函数:要检查的对象。新函数检查是否obj.key2存在。

回答by AdrianB

Try this:

尝试这个:

var parsedJSON = JSON.parse(stringJSON);
var value = parsedJSON['key2'];