简体   繁体   English

Javascript - 拆分并返回多个数组或字符串中的数组

[英]Javascript - Split and return array in multiple arrays or string

I have a json like this: 我有一个这样的json:

{"search":{"updated":"2018-11-07","name":[{"tag":"Peter"}]}}

... and I dynamically fetch the values and create a variable this: ...我动态获取值并创建一个变量:

var existingParams = [
"name",
"updated"].filter(field => getBody.search[field]);

var sqlVal = existingParams.map(field => {
 if (field === 'name') {
     function getValues(item, index) {
       var getVal = [item.tag];
       return "%" + getVal + "%";
     }
     console.log(name.map(getValues));
     return name.map(getValues);

   } else {
     return getBody.search[field];
   }
 })

For the above example I get for sqlVal: 对于上面的例子,我得到了sqlVal:

console.log(sqlVal);         

[ [ '%Peter%' ], '2018-11-07' ]

... which is fine. ......很好。

BUT, if I have two values: 但是,如果我有两个值:

{"search":{"updated":"2018-11-07","name":[{"tag":"Peter"},{"tag":"Jack"}]}} 

... I'm getting this structure: ......我得到了这个结构:

[ [ '%Peter%', '%Jack%' ], '2018-11-07' ]   

... but what I need is sth like: ......但我需要的是......

[ '%Peter%', '%Jack%', '2018-11-07' ]

... or: ... 要么:

[ ['%Peter%'], ['%Jack%'], '2018-11-07' ]

And in case of further eg 3 names: 如果还有3个名字:

{"search":{"updated":"2018-11-07","name":[{"tag":"Peter"},{"tag":"Jack"},{"tag":"Maria"}]}} 

... I need sth like: ......我需要......

[ '%Peter%', '%Jack%', '%Maria%', '2018-11-07' ]        

... or: ... 要么:

[ ['%Peter%'], ['%Jack%'], ['%Maria%'], '2018-11-07' ]

... and so on ... 等等

How do I need to adjust the above query to get this? 如何调整上述查询才能获得此信息?

If I understand your question correctly, then this problem can be solved via the Array#reduce() method. 如果我正确理解你的问题,那么这个问题可以通过Array#reduce()方法解决。

The general idea with this approach is to transform your input object to an array - the reduce operation can be used to do this, with the special-case rule of "flattening" the nested value on the name key into the final result: 这种方法的一般思想是将输入对象转换为数组 - 可以使用reduce操作来执行此操作,使用特殊情况规则将name键上的嵌套值“展平”为最终结果:

 var input = {"search":{"updated":"2018-11-07","name":[{"tag":"Peter"},{"tag":"Jack"}]}} var result = Object .entries(input.search) .reduce(function(result, entry) { const key = entry[0] const value = entry[1] if(key === 'name') { // When the 'name' key is encountered, handle the value // differently, by addting the items of this value array // to the result value.forEach(function(item) { result.push('%' + item.tag + '%') }) } else { // Append values for other keys directly to the result result.push(value) } return result }, []) console.log(result ) 

You could simply use Object.values + reduce for something like this: 你可以简单地使用Object.values + reduce 来做这样的事情:

 const json = { "search": { "updated": "2018-11-07", "name": [{ "tag": "Peter" }, { "tag": "Jack" }, { "tag": "Maria" }] } } const result = Object.values(json.search).reduce((r,c) => (Array.isArray(c) ? r.push(...c.map(({tag}) => `%${tag}%`)) : r.push(c), r),[]) console.log(result) 

If the order is important (names first then date) you could use reverse : 如果订单很重要(首先是名字,然后是日期),你可以使用反向

 const json = { "search": { "updated": "2018-11-07", "name": [{ "tag": "Peter" }, { "tag": "Jack" }, { "tag": "Maria" }] } } const result = Object.values(json.search).reverse().reduce((r,c) => (Array.isArray(c) ? r.push(...c.map(({tag}) => `%${tag}%`)) : r.push(c), r),[]) console.log(result) 

First of all you did not provide a Minimal, Complete, and Verifiable example so it is quite hard for me to figure out where you are running into issues. 首先,您没有提供最小,完整和可验证的示例,因此我很难弄清楚您遇到问题的位置。 For example, you are referencing existingParam but nowhere are they defined. 例如,您正在引用existingParam但它们没有定义。 This is key to understanding the problem because all of the code that you posted is heavily invested in the values and format of this value. 这是理解该问题的关键,因为您发布的所有代码都大量投入到该值的值和格式中。

Second, how are you parsing the JSON? 其次,你是如何解析JSON的? With the standard JSON#parse function you would get back an object with the same structure as your provided JSON. 使用标准的JSON#parse函数,您将获得一个与您提供的JSON结构相同的对象。 However, you are either not using this or you are mutating the object after it was parsed into a new format. 但是,您要么不使用它,要么在将对象解析为新格式后对其进行变更。 Either way, the object that JSON#parse returns for the provided JSON is not an array and therefor you cannot use Array#map on it. 无论哪种方式, JSON#parse为提供的JSON返回的对象都不是数组,因此您不能在其上使用Array#map

For the sake of being productive though I am going to try and explain how to do things. 为了提高工作效率,我将尝试解释如何做事。

JSON: JSON:

let data1 = '{"search":{"updated":"2018-11-07","name":[{"tag":"Peter"}]}}',
    data2 = '{"search":{"updated":"2018-11-07","name":[{"tag":"Peter"},{"tag":"Jack"}]}} ',
    data3 = '{"search":{"updated":"2018-11-07","name":[{"tag":"Peter"},{"tag":"Jack"},{"tag":"Maria"}]}}';

Now that we have our JSON data we need to parse it and store it as a JSON object. 现在我们有了JSON数据,我们需要解析它并将其存储为JSON对象。 To do so I am going to create a function; 为此,我将创建一个函数; this way the data can be passed to the same function and handled the same way but the implementation will stay the same. 这样,数据可以传递给同一个函数并以相同的方式处理,但实现将保持不变。 Also, since we are only looking at the values in the search property we are going to go ahead and jump right into it. 此外,由于我们只查看search属性中的值,因此我们将继续并直接进入search属性。

Parse the JSON: 解析JSON:

function parseResponse (response) {
    let parsedResponse = JSON.parse(response);
        parsedResponse = parsedResponse['search'];
}

Now that we have our function that takes our response and parses it we can then begin to sort through it to find and isolate the parts that we want. 既然我们的函数需要我们的响应并解析它,那么我们就可以开始对其进行排序,以找到并隔离我们想要的部分。 In this case we will add some code to loop through our properties and find the updated and name properties. 在这种情况下,我们将添加一些代码来遍历我们的属性并找到updatedname属性。

function parseResponse (response) {
    let parsedResponse = JSON.parse(response);
        parsedResponse = parsedResponse['search'];

    for (let prop in parsedResponse) {
        if (prop === 'updated') {
            // do stuff with 'updated'
        }

        if (prop === 'name') {
            // do stuff with 'name'
        }
    }
}

Because we want to return a result we are going to add a variable updated and names which will hold the values that we pull out of the string until we are ready to return them. 因为我们想要返回一个结果,所以我们将添加一个updated的变量和names ,它们将保存我们从字符串中提取的值,直到我们准备好返回它们为止。 Now that we have our loop and our temporary variables we can go ahead and pull the updated value out of our data and place it in the updated variable. 现在我们有了循环和临时变量,我们可以继续从数据中提取更新的值并将其放入updated变量中。

function parseResponse (response) {
    let parsedResponse = JSON.parse(response),
        updated = '',
        names = [];
        parsedResponse = parsedResponse['search'];

    for (let prop in parsedResponse) {
        if (prop === 'updated') {
            updated = parsedResponse[prop];
        }

        if (prop === 'name') {
            // do stuff with 'name'
        }
    }
}

With our updated value squared away we can jump into our names. 随着我们updated价值平方,我们可以跳到我们的名字。 Since you listed the format ['%name%', '%name%', '%name%'] first I am going to go ahead and show you how to do it this way. 由于您首先列出了格式['%name%', '%name%', '%name%']我将继续向您展示如何以这种方式执行此操作。 Here we are going to grab the property name , iterate through the names, grab the tag property, and then add the % s before pushing it to our names temporary variable. 在这里,我们将获取属性name ,遍历名称,获取tag属性,然后在将其推送到我们的names临时变量之前添加% s。

function parseResponse (response) {
    let parsedResponse = JSON.parse(response),
        updated = '',
        names = [];
        parsedResponse = parsedResponse['search'];

    for (let prop in parsedResponse) {
        if (prop === 'updated') {
            updated = parsedResponse[prop];
        }

        if (prop === 'name') {
            for (let i = 0; i < parsedResponse[prop].length; i++) {
                let name = parsedResponse[prop][i].tag;
                    name = '%' + name + '%';

                names.push(name);
            }
        }
    }
}

With everything in place all that is left is to assemble the result. 一切就绪,剩下的就是组合结果。 To do so we are going to flatten the array of names , add them to the array, and then add the updated value to the end before returning it. 为此,我们将展平names数组,将它们添加到数组中,然后在返回之前将updated值添加到结尾。 To flatten the array we are going to use the spread operator. 为了展平数组,我们将使用spread运算符。

function parseResponse (response) {
    let parsedResponse = JSON.parse(response),
        updated = '',
        names = [];
        parsedResponse = parsedResponse['search'];

    for (let prop in parsedResponse) {
        if (prop === 'updated') {
            updated = parsedResponse[prop];
        }

        if (prop === 'name') {
            for (let i = 0; i < parsedResponse[prop].length; i++) {
                let name = parsedResponse[prop][i].tag;
                    name = '%' + name + '%';

                names.push(name);
            }
        }
    }

    return [...names, updated];
}

With all of that set we can go ahead and call parseResponse() with data1 , data2 , or data3 and get back a response that looks like so: 通过所有这些设置,我们可以继续使用data1data2data3调用parseResponse()并获得如下所示的响应:

let data1 = '{"search":{"updated":"2018-11-07","name":[{"tag":"Peter"}]}}',
    data2 = '{"search":{"updated":"2018-11-07","name":[{"tag":"Peter"},{"tag":"Jack"}]}} ',
    data3 = '{"search":{"updated":"2018-11-07","name":[{"tag":"Peter"},{"tag":"Jack"},{"tag":"Maria"}]}}';

function parseResponse (response) {
    let parsedResponse = JSON.parse(response),
        updated = '',
        names = [];
        parsedResponse = parsedResponse['search'];

    for (let prop in parsedResponse) {
        if (prop === 'updated') {
            updated = parsedResponse[prop];
        }

        if (prop === 'name') {
            for (let i = 0; i < parsedResponse[prop].length; i++) {
                let name = parsedResponse[prop][i].tag;
                    name = '%' + name + '%';

                names.push(name);
            }
        }
    }

    return [...names, updated];
}

console.log(parseResponse(data1));
console.log(parseResponse(data2));
console.log(parseResponse(data3));

Spread operator can be used to flatten the result : Spread运算符可用于展平结果:

 var obj = {"search":{"updated":"2018-11-07","name":[{"tag":"Peter"},{"tag":"Jack"},{"tag":"Maria"}]}} var arr = [...obj.search.name.map(n => `%${n.tag}%`), obj.search.updated] console.log( arr ) 


Another alternative could be to extract during parsing : 另一种替代方法是在解析期间提取:

 var arr = [], json = '{"search":{"updated":"2018-11-07","name":[{"tag":"Peter"},{"tag":"Jack"},{"tag":"Maria"}]}}' JSON.parse(json, (k, v) => v.trim && arr.push(k === 'tag' ? `%${v}%` : v)) console.log( arr ) 

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

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