简体   繁体   English

JavaScript:通过使用一个 object 获取数组的属性/值来动态构建条件

[英]JavaScript: Dynamically build a condition by fetching properties/values of an array with one object

I am trying to make a script which我正在尝试制作一个脚本

  1. Gets the current URL (url1 variable in the example) which contains params/values and which can be entirely different each time - OK获取当前的 URL(示例中的 url1 变量),其中包含参数/值并且每次都可以完全不同 - 好的
  2. I extract both params and values and create an object from them with keys/values - OK我提取参数和值,并使用键/值从它们创建 object - 好的
  3. I build a condition for later use, dynamically which does not expect a certain number of pairs, so it gets built from whatever it finds in the object - NOT OK我建立了一个供以后使用的条件,动态地它不期望一定数量的对,所以它是从它在object中找到的任何东西中构建的 - 不好

. .

let url1 = 'http://localhost/myproject/results?id=0001&area=eiffel+tower&city=Paris&whatever=else';

function URLToArray(url) {
    var request = {};
    var pairs = url.substring(url.indexOf('?') + 1).split('&');
    for (var i = 0; i < pairs.length; i++) {
        if(!pairs[i])
            continue;
        var pair = pairs[i].split('=');
        request[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
     }
     console.log(request); // { id: '0001', area: 'eiffel+tower', city: 'Paris', whatever: 'else' }
     return(request);
}

let paramsObj = URLToArray(url1);

console.log(paramsObj)  // { id: '0001', area: 'eiffel+tower', city: 'Paris', whatever: 'else' }

// Step 3 below, where the issue is and I expect
// id === '0001' && area === 'eiffel+tower' && city === 'Paris' && something === 'else'

paramsObj.forEach((item) => {
  let condition = '';
  let keys = Object.keys(item);
  keys.map((k) => {
    if (condition) {
      condition += ` && ${k} === '${item[k]}'`
} else {
  condition = `${k} === '${item[k]}'`
    }

  })
  console.log(condition);
})

Outputs输出

paramsObj.forEach((item) => { TypeError: paramsObj.forEach is not a function at Object.<anonymous>

Expected on console.log(condition)预期console.log(condition)

id === '0001' && area === 'eiffel+tower' && city === 'Paris' && whatever === 'else'

Note : if the object was inside [ ] brackets, the output would somehow be the expected one.注意:如果 object 在[ ]括号内,则 output 会以某种方式成为预期的。 However URLToArray(url) outputs object without brackets.但是URLToArray(url)输出 object 不带括号。

The URLToArray() returns an object and not an array. URLToArray()返回 object 而不是数组。 You cannot use forEach on an instance of an object.您不能在 object 的实例上使用forEach

Instead, you may want to iterate over keys, like the following:相反,您可能想要遍历键,如下所示:

Object.keys(paramsObj).forEach((key) => {
  const value = paramsObj[key];
  let condition = '';
  if (condition) {
    condition += ` && ${key} == ${value}`;
  } else {
    condition = `${key} == ${value}`;
  }
);

ForEach method is an array method and you're trying to use it on an object, you should probably just create a function that takes in an object as one of its parameters. ForEach 方法是一个数组方法,并且您尝试在 object 上使用它,您可能应该只创建一个 function ,它将 object 作为其参数之一。

 function ProcessItem(item) { let condition = ''; let keys = Object.keys(item); keys.map((k) => { if (condition) { condition += ` && ${k} === '${item[k]}'` } else { condition = `${k} === '${item[k]}'` } }) console.log(condition); }

Consider the following.考虑以下。

 var url1 = 'http://localhost/myproject/results?id=0001&area=eiffel%20tower&city=Paris&whatever=else'; function getQueryFromURL(u) { var r = {}; var parts; if (u.indexOf("?") > -1) { parts = u.substr(u.indexOf("?") + 1).split("&"); $.each(parts, function(i, v) { r[v.split("=")[0]] = decodeURI(v.split("=")[1]); }); } return r; } function objJoin(o, a, b) { var r = ""; var arr; $.each(o, function(k, v) { if (r.length == 0) { r += [k, a, v].join(" "); } else { r += " " + [b, k, a, v].join(" "); } }); return r; } let paramsObj = getQueryFromURL(url1); console.log(paramsObj); console.log(objJoin(paramsObj, "===", "&&"));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

This does not do anything vastly different, it just makes a bit better use of the tools at hand to get the same result.这并没有太大的不同,它只是更好地利用手头的工具来获得相同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM