programing

JSON 개체 내 Javascript 검색

sourcejob 2023. 2. 16. 21:36
반응형

JSON 개체 내 Javascript 검색

응용 프로그램에 JSON 문자열/오브젝트가 있습니다.

{"list": [
    {"name":"my Name","id":12,"type":"car owner"},
    {"name":"my Name2","id":13,"type":"car owner2"},
    {"name":"my Name4","id":14,"type":"car owner3"},
    {"name":"my Name4","id":15,"type":"car owner5"}
]}

어플리케이션에 필터 박스가 있어서 이름을 입력하면 오브젝트를 필터링하여 결과를 표시해야 합니다.

예를 들어 사용자가 "name"을 입력하고 검색을 누르면 MySQL 검색과 마찬가지로 JSON 개체에서 전체 이름을 검색하여 어레이를 반환해야 합니다.

json 개체를 문자열로 필터링하고 어레이를 반환하는 것입니다.

어레이를 루프하여 일치하는 항목을 찾을 수 있습니다.

var results = [];
var searchField = "name";
var searchVal = "my Name";
for (var i=0 ; i < obj.list.length ; i++)
{
    if (obj.list[i][searchField] == searchVal) {
        results.push(obj.list[i]);
    }
}

당신을 검색할 수 있는 기본 제공 기능이 있는지 묻는다면 없습니다.기본적으로 또는 정규 표현식을 사용하여 어레이를 루프하여 문자열을 테스트합니다.

루프에는 적어도3가지 선택지가 있습니다.

  1. 따분한 늙은이for고리.

  2. ES5 지원 환경(또는 심 포함)에서는,

  3. jQuery를 사용하고 있기 때문에,

따분한 옛날for루프의 예:

function search(source, name) {
    var results = [];
    var index;
    var entry;

    name = name.toUpperCase();
    for (index = 0; index < source.length; ++index) {
        entry = source[index];
        if (entry && entry.name && entry.name.toUpperCase().indexOf(name) !== -1) {
            results.push(entry);
        }
    }

    return results;
}

어디서 그런 말을 할 수 있죠?obj.list~하듯이source원하는 이름의 fragment를 지정합니다.name.

또는 공백 항목 또는 이름이 없는 항목이 있을 수 있는 경우if대상:

        if (entry && entry.name && entry.name.toUpperCase().indexOf(name) !== -1) {

Array#filter예:

function search(source, name) {
    var results;

    name = name.toUpperCase();
    results = source.filter(function(entry) {
        return entry.name.toUpperCase().indexOf(name) !== -1;
    });
    return results;
}

또한 빈 엔트리가 있는 경우(예:undefined(실종과 달리)filter누락된 엔트리를 건너뜁니다). 내부 복귀를 다음과 같이 변경합니다.

        return entry && entry.name && entry.name.toUpperCase().indexOf(name) !== -1;

jQuery.map예(여기서 가정합니다)jQuery=$여느 때처럼; 변하다$로.jQuery사용하고 있다면noConflict):

function search(source, name) {
    var results;

    name = name.toUpperCase();
    results = $.map(source, function(entry) {
        var match = entry.name.toUpperCase().indexOf(name) !== -1;
        return match ? entry : null;
    });
    return results;
}

(그리고 다시 추가)entry && entry.name &&(필요한 경우)

데이터를 변수에 저장하기만 하면 JavaScript의 find(레코드의 단일 객체 가져오기) 또는 filter(레코드의 단일 배열 가져오기) 메서드를 사용할 수 있습니다.

예:-

let data = {
 "list": [
   {"name":"my Name","id":12,"type":"car owner"},
   {"name":"my Name2","id":13,"type":"car owner2"},
   {"name":"my Name4","id":14,"type":"car owner3"},
   {"name":"my Name4","id":15,"type":"car owner5"}
]}

다음 명령어 onkeyup을 사용하거나

한 가지 물건을 얻다

data.list.find( record => record.name === "my Name")

단일 배열 개체를 가져오다

data.list.filter( record => record.name === "my Name")

javascript를 사용하는 SQL 라이크 데이터베이스인 PaulGuojSQL을 사용합니다.예를 들어 다음과 같습니다.

var db = new jSQL();
db.create('dbname', testListData).use('dbname');
var data = db.select('*').where(function(o) {
    return o.name == 'Jacking';
}).listAll();

JSON과 함께 작업하기 위해 regex를 조정했습니다.

먼저 JSON 개체를 문자열화합니다.그런 다음 일치하는 서브스트링의 시작과 길이를 저장해야 합니다.예를 들어 다음과 같습니다.

"matched".search("ch") // yields 3

JSON 문자열의 경우, 이것은 완전히 동일하게 동작합니다(쉼표와 괄호를 명시적으로 검색하지 않는 한). 이 경우 정규식을 수행하기 전에 JSON 개체의 사전 변환을 권장합니다(예: think :, {, }).

다음으로 JSON 개체를 재구성해야 합니다.내가 작성한 알고리즘은 일치 인덱스에서 반복적으로 뒤로 이동함으로써 JSON 구문을 검출함으로써 이를 실현합니다.예를 들어 의사 코드는 다음과 같습니다.

find the next key preceding the match index, call this theKey
then find the number of all occurrences of this key preceding theKey, call this theNumber
using the number of occurrences of all keys with same name as theKey up to position of theKey, traverse the object until keys named theKey has been discovered theNumber times
return this object called parentChain

이 정보를 사용하여 regex를 사용하여 JSON 개체를 필터링하여 키, 값 및 부모 개체 체인을 반환할 수 있습니다.

제가 작성한 라이브러리와 코드는 http://json.spiritway.co/ 에서 보실 수 있습니다.

애플리케이션의 여러 곳에서 이 작업을 수행하는 경우 어레이에 의해 호출되는 커스텀 검색 기능을 생성하기 때문에 클라이언트 측 JSON 데이터베이스를 사용하는 것이 좋습니다.filter()는 지저분하고 유지보수가 용이하지 않습니다.

Forerunner 확인DB는 매우 강력한 클라이언트 측 JSON 데이터베이스 시스템을 제공하며 원하는 작업을 정확하게 수행할 수 있는 매우 간단한 쿼리 언어를 포함합니다.

// Create a new instance of ForerunnerDB and then ask for a database
var fdb = new ForerunnerDB(),
    db = fdb.db('myTestDatabase'),
    coll;

// Create our new collection (like a MySQL table) and change the default
// primary key from "_id" to "id"
coll = db.collection('myCollection', {primaryKey: 'id'});

// Insert our records into the collection
coll.insert([
    {"name":"my Name","id":12,"type":"car owner"},
    {"name":"my Name2","id":13,"type":"car owner2"},
    {"name":"my Name4","id":14,"type":"car owner3"},
    {"name":"my Name4","id":15,"type":"car owner5"}
]);

// Search the collection for the string "my nam" as a case insensitive
// regular expression - this search will match all records because every
// name field has the text "my Nam" in it
var searchResultArray = coll.find({
    name: /my nam/i
});

console.log(searchResultArray);

/* Outputs
[
    {"name":"my Name","id":12,"type":"car owner"},
    {"name":"my Name2","id":13,"type":"car owner2"},
    {"name":"my Name4","id":14,"type":"car owner3"},
    {"name":"my Name4","id":15,"type":"car owner5"}
]
*/

면책사항:저는 ForerunnerDB 개발자입니다.

오브젝트 스캔을 사용한 반복적인 솔루션을 다음에 나타냅니다.장점은 필터 기능에서 다른 처리를 쉽게 수행하고 경로를 보다 읽기 쉬운 형식으로 지정할 수 있다는 것입니다.다만, 의존 관계를 도입하는 것에는 트레이드 오프가 있기 때문에, 실제로 사용 사례에 따라 다릅니다.

// const objectScan = require('object-scan');

const search = (haystack, k, v) => objectScan([`list[*].${k}`], {
  rtn: 'parent',
  filterFn: ({ value }) => value === v
})(haystack);

const obj = { list: [ { name: 'my Name', id: 12, type: 'car owner' }, { name: 'my Name2', id: 13, type: 'car owner2' }, { name: 'my Name4', id: 14, type: 'car owner3' }, { name: 'my Name4', id: 15, type: 'car owner5' } ] };

console.log(search(obj, 'name', 'my Name'));
// => [ { name: 'my Name', id: 12, type: 'car owner' } ]
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan@13.8.0"></script>

면책사항:는 객체 스캔의 저자입니다.

라이브러리 Js-Search를 사용하여 모든 속성의 값을 사용하여 json 개체를 필터링할 수 있습니다.

다음과 같이 시험해 보십시오.

function search(data,search) {
    var obj = [], index=0;
    for(var i=0; i<data.length; i++) {
      for(key in data[i]){
         if(data[i][key].toString().toLowerCase().indexOf(search.toLowerCase())!=-1) {
                obj[index] = data[i];
                index++;
                break;
         }
     }
     return obj;
}
console.log(search(obj.list,'my Name'));

언급URL : https://stackoverflow.com/questions/10679580/javascript-search-inside-a-json-object

반응형