sourcetip

JavaScript 또는 jQuery에서 JSON 데이터를 필터링하려면 어떻게 해야 합니까?

fileupload 2023. 3. 19. 18:25
반응형

JavaScript 또는 jQuery에서 JSON 데이터를 필터링하려면 어떻게 해야 합니까?

Javascript 또는 jQuery를 사용하여 JSON 데이터를 필터링하는 방법은 무엇입니까?

다음은 JSON 데이터입니다.

[{"name":"Lenovo Thinkpad 41A4298","website":"google"},
{"name":"Lenovo Thinkpad 41A2222","website":"google"},
{"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"},
{"name":"Lenovo Thinkpad 41A424448","website":"google"},
{"name":"Lenovo Thinkpad 41A429rr8","website":"ebay"},
{"name":"Lenovo Thinkpad 41A429ff8","website":"ebay"},
{"name":"Lenovo Thinkpad 41A429ss8","website":"rediff"},
{"name":"Lenovo Thinkpad 41A429sg8","website":"yahoo"}]

JavaScript:

obj1 = JSON.parse(jsondata);

이제 나는 웹사이트가 "yahoo"와 같은 이름과 웹사이트 데이터만 원한다.

다음과 같이 해야 합니다. (구글 검색의 경우)

$([
  {"name":"Lenovo Thinkpad 41A4298","website":"google222"},
  {"name":"Lenovo Thinkpad 41A2222","website":"google"}
  ])
    .filter(function (i,n){
        return n.website==='google';
    });

나은 솔루션: (Salman's)

$.grep( [{"name":"Lenovo Thinkpad 41A4298","website":"google"},{"name":"Lenovo Thinkpad 41A2222","website":"google"}], function( n, i ) {
  return n.website==='google';
});

http://jsbin.com/yakubixi/4/edit

오래된 브라우저를 대상으로 하고 심을 사용하지 않는 한 jQuery는 필요 없습니다.

var yahooOnly = JSON.parse(jsondata).filter(function (entry) {
    return entry.website === 'yahoo';
});

ES2015년:

const yahooOnly = JSON.parse(jsondata).filter(({website}) => website === 'yahoo');

다음 코드를 사용할 수 있습니다.

var data = [{"name":"Lenovo Thinkpad 41A4298","website":"google"},
{"name":"Lenovo Thinkpad 41A2222","website":"google"},
{"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"},
{"name":"Lenovo Thinkpad 41A424448","website":"google"},
{"name":"Lenovo Thinkpad 41A429rr8","website":"ebay"},
{"name":"Lenovo Thinkpad 41A429ff8","website":"ebay"},
{"name":"Lenovo Thinkpad 41A429ss8","website":"rediff"},
{"name":"Lenovo Thinkpad 41A429sg8","website":"yahoo"}]

var data_filter = data.filter( element => element.website =="yahoo")
console.log(data_filter)

다른 키로 필터링할 수도 있습니다.

데이터:

var my_data = [{"name":"Lenovo Thinkpad 41A4298","website":"google"},
{"name":"Lenovo Thinkpad 41A2222","website":"google"},
{"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"},
{"name":"Lenovo Thinkpad 41A424448","website":"google"},
{"name":"Lenovo Thinkpad 41A429rr8","website":"ebay"},
{"name":"Lenovo Thinkpad 41A429ff8","website":"ebay"},
{"name":"Lenovo Thinkpad 41A429ss8","website":"rediff"},
{"name":"Lenovo Thinkpad 41A429sg8","website":"yahoo"}];

사용방법:

//We do that to ensure to get a correct JSON
var my_json = JSON.stringify(my_data)
//We can use {'name': 'Lenovo Thinkpad 41A429ff8'} as criteria too
var filtered_json = find_in_object(JSON.parse(my_json), {website: 'yahoo'});

필터 기능

function find_in_object(my_object, my_criteria){

  return my_object.filter(function(obj) {
    return Object.keys(my_criteria).every(function(c) {
      return obj[c] == my_criteria[c];
    });
  });

}

jQuery함수는 다음과 같이 사용할 수 있습니다.

데이터 정의:

var jsonStr = '[{"name":"Lenovo Thinkpad 41A4298,"website":"google"},{"name":"Lenovo Thinkpad 41A2222,"website":"google"},{"name":"Lenovo Thinkpad 41Awww33,"website":"yahoo"},{"name":"Lenovo Thinkpad 41A424448,"website":"google"},{"name":"Lenovo Thinkpad 41A429rr8,"website":"ebay"},{"name":"Lenovo Thinkpad 41A429ff8,"website":"ebay"},{"name":"Lenovo Thinkpad 41A429ss8,"website":"rediff"},{"name":"Lenovo Thinkpad 41A429sg8,"website":"yahoo"}]';

JSON 문자열을 JSON 개체로 구문 분석:

var json = JSON.parse(jsonStr);

반복 및 필터링:

$.each(JSON.parse(json), function (idx, obj) {
    if (obj.website == 'yahoo') {
        // do whatever you want
    }
});

값은 해석 중에 취득할 수 있습니다.

var yahoo = [], j = `[{"name":"Lenovo Thinkpad 41A4298","website":"google"},
{"name":"Lenovo Thinkpad 41A2222","website":"google"},
{"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"},
{"name":"Lenovo Thinkpad 41A424448","website":"google"},
{"name":"Lenovo Thinkpad 41A429rr8","website":"ebay"},
{"name":"Lenovo Thinkpad 41A429ff8","website":"ebay"},
{"name":"Lenovo Thinkpad 41A429ss8","website":"rediff"},
{"name":"Lenovo Thinkpad 41A429sg8","website":"yahoo"}]`

var data = JSON.parse(j, function(key, value) { 
      if ( value.website === "yahoo" ) yahoo.push(value); 
      return value; })

console.log( yahoo )

질문에 JS 또는 jQuery라고 명시되어 있는 것은 알고 있습니다만, 어쨌든 lodash를 사용하는 것은 다른 검색자에게 있어서 항상 문제가 된다고 생각합니다.

소스 문서에서:

var users = [
  { 'user': 'barney', 'age': 36, 'active': true },
  { 'user': 'fred',   'age': 40, 'active': false }
];

_.filter(users, function(o) { return !o.active; });
// => objects for ['fred']

// The `_.matches` iteratee shorthand.
_.filter(users, { 'age': 36, 'active': true });
// => objects for ['barney']

// The `_.matchesProperty` iteratee shorthand.
_.filter(users, ['active', false]);
// => objects for ['fred']

// The `_.property` iteratee shorthand.
_.filter(users, 'active');
// => objects for ['barney']

따라서 첫 번째 질문에 대한 해답은 라이너 하나뿐입니다.

var result = _.filter(data, ['website', 'yahoo']);

json 객체를 반복하여 관심 있는 각 값인 '웹 사이트'를 검색하면 해당 값을 반환하거나 원하는 작업을 수행할 수 있습니다.지금은 콘솔에 해당 요소만 기록합니다.

jsonObj.forEach(function (element, index) {
    if(element['website'] === 'yahoo'){
        console.log('found', element)   
    }
})

언급URL : https://stackoverflow.com/questions/23720988/how-to-filter-json-data-in-javascript-or-jquery

반응형