skip to Main Content

I get through ajax a string consisting of two elements that I can’t separate from each other.

{"0":"04.14.23","date":"04.14.23","1":"nixanosize","login":"nixanosize","2":"xori","name_company":"xori","3":"qqqq","name":"qqqq","4":"","inn":"","5":"","info":"","6":"","boss":"","7":"","street":"","8":"","number":"","9":"","comment_company":""}
{"0":"04.14.23","date":"04.14.23","1":"nixanosize","login":"nixanosize","2":"xori","name_company":"xori","3":"","name":"","4":"","inn":"","5":"2day","info":"2day","6":"","boss":"","7":"","street":"","8":"","number":"","9":"","comment_company":""}

Help me remove duplicate elements and move this string to an array with two attachments, so that after I can go through the while loop and take the necessary data.

In short, I can’t process this line correctly.

[["date":"04.14.23","login":"nixanosize","name_company":"xori","name":"qqqq","inn":"","info":"","boss":"","street":"","number":"","comment_company":""],
["date":"04.14.23","login":"nixanosize","name_company":"xori","name":"qqqq","inn":"","info":"","boss":"","street":"","number":"","comment_company":""]]

This is an approximate view of what I would like to come to.

Nevertheless, it would be nice to hear your suggestions.

I tried to use regular expressions and .split(), but in my hands it did not give the desired result.

2

Answers


  1. Chosen as BEST ANSWER

    In my case, the question was originally posed incorrectly. Instead of changing the resulting string, I tried to change the output.

    In this case, I get the correct JSON data that I can use. It was worth changing the PhP script, and not torturing yourself and js.

    $array[] = $row; echo json_encode($array);

    Upadate:

    $array = array($row['date'],$row['login'],$row['name_company']); echo json_encode($array);

    This decision prompted me @pilchard


  2. As you want to remove a duplicate properties from an object and as per the object structure you mentioned in the post. I can see that we have a numeric key for each duplicated property. So what we can do is that we can remove those numeric key properties from an object with the help of regex String.match() method and then push that into an array.

    Live Demo :

    const str = '{"0":"04.14.23","date":"04.14.23","1":"nixanosize","login":"nixanosize","2":"xori","name_company":"xori","3":"qqqq","name":"qqqq","4":"","inn":"","5":"","info":"","6":"","boss":"","7":"","street":"","8":"","number":"","9":"","comment_company":""}';
    
    const jsonObj = JSON.parse(str);
    
    const arr = [];
    
    Object.keys(jsonObj).forEach(key => {
        if (key.match(/^[0-9]+$/)?.length) {
        delete jsonObj[key]
      }
    });
    
    arr.push(jsonObj);
    
    console.log(arr);

    Note : The output you are expecting is not a valid JSON, It should be an array of objects instead of array of arrays.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search