Mi Lugarcito
array 배열 구조, for 구문, Object의 Keys Value -> case by case -> map, filter 정리 블로그! 본문
array 배열 구조, for 구문, Object의 Keys Value -> case by case -> map, filter 정리 블로그!
selene park 2022. 3. 3. 08:41https://milugarcito.tistory.com/404
JavaScript - Array
'use strict'; //Array //1. Declaration const arr1 = new Array(); const arr2 = [1,2]; //2. Index position const fruits = ['🍏', '🍌']; console.log(fruits); console.log(fruits.length); console.log(fru..
milugarcito.tistory.com
https://milugarcito.tistory.com/613
Axios 통신 - Object with array key and array value 공부
https://doogle.link/axios-%EC%82%AC%EC%9A%A9%EC%8B%9C-%ED%8F%BC-%EB%8D%B0%EC%9D%B4%ED%84%B0-%EC%A0%84%EC%86%A1%ED%95%98%EA%B8%B0-%ED%8C%8C%EC%9D%BC-%EC%97%85%EB%A1%9C%EB%93%9C/ axios 사용시 폼 데이..
milugarcito.tistory.com
https://milugarcito.tistory.com/519
TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView.
config.js 에서 mysql 비밀번호 숫자를 "" string 으로 변환 시켜줘야한다. { "development": { "username": "root", "password": "1234", "database": "react-nodebird", "host": "127.0.0.1", "dialect": "mysq..
milugarcito.tistory.com
Token with Nuxt Cookie 정리하기,
셋인터벌 정리하기,
항진씨코드, 재훈씨 코드, 재훈씨 상품코드 정리
async await 공부하기
promise 공부하기
promise all 공부하기
🖤 CASE 0 --->
For 구문 함수 차이점
FOR..IN
//for in
for(let item of coupons){
console.log(item,'for in 구문')
}
NORMAL FOR 1개
//normal for
for(let item2=0; item2 <coupons.length; item2++ ){
console.log(coupons[item2], 'for 일반구문')
}
중첩 FOR 구문
this.shopList = res.data;
console.log(res.data,'getShopList')//[{},{},{}]
for(let i=0; i<this.shopList.length; i++){
// shopList: [], // 샵리스트
// newList: {}, // 새로 만들어주기
// newListA: {},
console.log(this.shopList[i].category_nm,'this.shopList[i].category_nm') // 따로 나오는걸 일단 배열로 넣어주기
if(!this.newList[this.shopList[i].category_nm]){
// 없으면 그냥 빈배열 처리
this.newList[this.shopList[i].category_nm] = [];
}{
// { [{ }] }
// 있으면 {} 안에 [{}] 넣기.. -> { [{...}], [{...}],[{...}], ..... }
// { 메인카테1 : [{...}], 메인카테2 : [{...}], 메인카테3 : [{...}] }
this.newList[this.shopList[i].category_nm].push(this.shopList[i])
}
}
console.log(this.newList, "결과값")
this.$forceUpdate();
this.newListA = this.newList
// {{}} 이렇게 되는게 아니라 -> 한개로 합쳐짐 -> {}
// 배열도 마찬가지.. [[]] 되는게 아니라 -> 한개로 합쳐짐 -> []
console.log(this.newListA,'this.newListA')
FOREACH
//foreach
coupons.forEach((coupon)=> console.log(coupon,'forEach 구문'))
🖤 CASE 1 --->
for of & push 구조
[ { }, { }, { } ] -> [ 'aaa', 'bbb', 'ccc', 'ddd'] 구조, 특정 object의 value 값만 뽑아서 배열로 만들기
for(let item of coupons) 이렇게 써야지 전체 배열안에 있는 각각의 { } 를 뽑아옴
console.log(coupons,'coupons@@@@')// [{},{},{}]
let couponArr = [];
for(let item of coupons){
couponArr.push(item.coupon_no)
}
console.log(couponArr,'couponArr@@@')// [{},{},{}] -> ['aaa','bbb','ccc','ddd']
[{},{},{}]
가공한 결과값 : ['aaa','bbb','ccc','ddd']
🖤 CASE 2 --->
filter & push 써서 원래는 [ [ { } ], [ { } ], [ { }] ] 이렇게 나오는걸 -> [ { }, { }, { } ] 이렇게 만드는 방법
2개의 [ { }, { }, { } ] 결과구조를 특정 value 값을 기준으로 2개 api 를 합쳐서 object로 새로 만든 후, 새로운 배열1개 안에 여러 objects { }, { }, { } 만들기 .....
api 결과값 1
api 결과값 2
가공한 결과값 1--> [ { }, { }, { } ]
const adminRes = await this.$axios.get('/myPage/retrieveListOfCoupons');
let adminCoupons = adminRes.data.data.coupons;
console.log(adminCoupons,'adminCoupons@@@@@')
let couponsArrResult = [];
for (let coupon_no of couponArr){
let [__] = (
adminCoupons.filter(coupon=>{
return coupon.coupon_no == coupon_no
})
)
couponsArrResult.push(__)// [ { }, { }, { } ] -> 이거를 let [ 아무거나 ] 이렇게 선언해주면 [] 제거해줘서 { }, { }, { } 이렇게 나옴
}
console.log(couponsArrResult,'couponsArrResult@@@@')
가공한 결과값2 -> [ [{ }] , [{ }] , [{ }] ]...
let couponsArrResult = [];
for(let coupon_no of couponArr){
let test = adminCoupons.filter(item2=>{
return item2.coupon_no === coupon_no
})
couponsArrResult.push(test) // 이렇게 하면 filter 함수가 []로 넘겨줘서 -> let test = [{}], [{}], [{}]... 이렇게 됨
}
console.log(couponsArrResult,'couponsArrResult') // [[{}], [{}], [{}]]...
가공한 결과값3 -> 이중 for구문 돌리는 방법
for(let i=0; i<this.user_coupons.length; i++){
for(let j=0; j<this.shop_coupons.length; j++){
if(this.user_coupons[i].coupon_no === this.shop_coupons[j].coupon_no){
this.user_data.coupons.push(this.shop_coupons[j])
}
}
}
// 큰 배열2개를 coupon_no 기준으로 합쳐서 새로운 배열 생성 (기준 : 내가 추출하고자 하는 배열을 기준)
console.log(this.user_data.coupons,'this.user_data.coupons')
가공한 결과값4
let send_data = []
await this.$axios.get(`/admin/retrieveListOfCustomerInformation?search_field=name&keyword=${this.search_keyword}`)
.then(res => {
for (let data of res.data.data.customersprivacy){
send_data =
[
{
name: data.name,
phone: data.cellphone,
member_id: data.member_id,
createdAt: data.created_date.slice(0, 10),
},
...send_data
]
// 검색한 결과값들이 -> [[{ }], [{ }] ....] -> 원래는 이렇게 출력되는것인데 -> 먼저 let send_data = [] 라고 선언해줘서 -> [{ }], [{ },{ }], [{ },{ },{ }], [{ },{ },{ },{ }].. 이렇게 배열 길이만큼 출력됨
console.log(send_data,'send_data')
}
}).catch(err => {
console.log(err);
})
🖤 CASE 3 --->
[ "Object Keys" : {"Object Keys " : "Object Values" }, {"Object Keys " : "Object Values" } , ...]
가공한 결과값 -> ["6071937532900000009" : {"aaa" : "aaa", "bbb" : "bbb"}]

const adminRes = await this.$axios.get('/myPage/retrieveListOfCoupons');
let adminCoupons = adminRes.data.data.coupons; // [{},{},{}]
let resultArr =[];
for(let coupon of adminCoupons){
let arrObject = coupon.coupon_no;
let arrKeys = {"available_day_from_issued" : coupon.available_day_from_issued , "available_date" : coupon.available_date }
console.log(arrObject,'arrObject') // "object의 keys 값으로 들어갈것"
console.log(arrKeys,'arrKeys')// "object의 value 값으로 들어갈것"
let temp = {};
// 형식을 {} 로 맞춰주기
temp[arrObject] =arrKeys; // { ["111", "222", "333"] } = {"available_day_from_issued" : coupon.available_day_from_issued , "available_date" : coupon.available_date }
resultArr.push(temp)
}
console.log(resultArr,'resultArr')
🖤 CASE 4 --->
Filter & Map & Reduce 함수 차이점
https://inpa.tistory.com/entry/JS-%F0%9F%93%9A-map-%EA%B3%BC-filter-%EC%B0%A8%EC%9D%B4
[JS] 📚 자바스크립트 map 과 filter 차이
map() vs filter() 둘은 매우 비슷하게 생겼다. 콜백함수의 인자도 거의 똑같고 생김새도 완전 판박이라 할수 있다. 다만 각 함수의 리턴하는 기능이 다르다고 볼수 있다. .map() callback 함수를 각각의
inpa.tistory.com
https://velog.io/@tjdud0123/javascript-map-filter-%ED%95%A8%EC%88%98
[ javascript ] map, filter 함수
javascript의 map, filter 함수를 알아봅시다 map과 filter의 공통점과 차이점, 응용, 예시 등
velog.io
공통점 : 기존 배열을 건드리지 않고, 각각의 배열의 요소들을 순회한후 "새로운 배열을 리턴" 함
-> Filter ?
조건문을 만족한 요소들을 반환함, true를 반환하면 요소를 유지하고, false를 반환하면 버림
즉, 리턴 값의 boolean이 true인 값만 가지고 배열을 만듬 (false, undefined 제외시킴)
const adminRes = await this.$axios.get('/myPage/retrieveListOfCoupons');
let adminCoupons = adminRes.data.data.coupons; // [{},{},{}]
let couponsArrResult = [];
for (let coupon_no of couponArr){
let [__] = (
adminCoupons.filter(coupon=>{
return coupon.coupon_no == coupon_no
})
)
couponsArrResult.push(__)
}
-> Map ?
콜백 함수가 적용된 새 요소들을 반환함
즉, 리턴 값의 boolean값을 리턴해 배열(false, undefined 도 배열에 넣어버림)
false or undefined 값을 null로 표현해야하는경우 MAP 써야함
<Map 함수 예제 1>
this.user_info.coupons = couponsArrResult.map(item => {
return {
...item, //couponsArrResult 배열의 각 {},{},{}...
//각 {},{},{} 의 key값인 coupon_image_path 를 순서대로 돌면서 검사
coupon_image_path: !!item.coupon_image_path ? (item.coupon_image_path.split('http')[0] + 'https') + (item.coupon_image_path.split('http')[1]) : null
}
}); // api 2개 합친값
<Map 함수 예제 2>
console.log(res.data,'res getShopMenu @@@@@@@@@@@@@@@') // [{},{}..]
this.shopMenu = res.data.map((item,index)=>{
console.log(item,'item @@@')//{idx: 1, category_nm: 'Online Marketplace'} -> 큰 배열안의 각 오브젝트들 출력
console.log(index,'index @@@')//0, 1, 2, 3, .... -> 그냥 큰 배열안에 있는 각 오브젝트들 순서를 출력
return{
title : item.category_nm,
}
})
//1 - check
for(var key in this.orderStatusList){
for(var i=0;i<this.orderStatusList[key].length;i++){
this.orderStatusList[key][i].checked = false;
}
}
//1 - check
this.orderSummaryList = targetItems;
//1 - check
console.log(targetItems,'1 - check / targetItems =====')
//2 - check
console.log(Object.keys(this.orderSummaryList), '2 - check / targetItems ====')
//3 - check
for(let item in this.orderSummaryList){
this.order_code.push(item)
}
//3 - check
console.log(this.order_code,'3 - check / this.order_code')
🖤 CASE 5 --->
두 배열을 하나의 오브젝트로 합치기
<Javascript> Object를 Array처럼 순회하기
기본적으로 Array는 순서가 있는 데이터가 인덱스 순서에 따라 안에 정렬되어 있어, for (var i; i < arrary.length ; i++) 식으로 순회하거나 .forEach, .map, .find, .reduce 등 유용한 기능을 활용가능하다.그
velog.io
https://developer-talk.tistory.com/303
[JavaScript]객체를 배열로 변환하는 방법
이번 포스팅에서는 JavaScript에서 객체를 배열로 변환하는 방법들을 소개합니다. 고전적인 방법 JavaScript에서 객체를 배열로 변환하는 고전적인 방법은 객체의 속성을 반복적으로 접근하여 push()
developer-talk.tistory.com
https://ingnoh.tistory.com/133
[JS] 두 배열을 하나의 오브젝트로 합치기
어쩌다가 오브젝트의 key를 모아둔 배열과 values를 모아둔 배열을 합쳐야한다고 할 때, 다음과 같이 해볼 수 있다. const keys = ['k1', 'k2']; const values = ['injuk', 'ingnoh']; const result = keys.reduce..
ingnoh.tistory.com
https://goddino.tistory.com/198
[js] 객체를 배열로 바꾸는 법, 배열을 객체로 바꾸는 법
자바스크립트 데이터에서 객체를 배열로, 배열을 객체로 바꾸는 방법입니다. 실무에서는 화면에서 게시판, 테이블과 같은 형태의 출력을 위해, 또는 서버 전송을 위해 자주 객체를 배열로 변환
goddino.tistory.com
//이거랑 새로 업뎃 되는거랑 비교하기
let old_city = [];
for(let one of user_cate_id){
old_city.push(one.id)
}
const total = old_city.reduce((before,cur, idx)=>{
before[cur] = city[idx];
return before;
}, new Object);
console.log(total,'total')
console.log(Object.keys(total),'keys')
console.log(Object.values(total),'values')
배열의 중복 제거, 2차원 배열의 중복 제거
JavaScript 배열의 중복 제거, 2차원 배열의 중복 제거
javascript 다양한 배열 중복 제거 방법(filter, set, forEach), 2차원 배열의 중복 제거 방법
velog.io
2차원 배열을 1차원 배열로 변환
https://codechacha.com/ko/javascript-flatten-array/
JavaScript - 2차원 배열을 1차원 배열로 변환, 2가지 방법
자바스크립트에서 2차원 배열을 1차원 배열로 변환하는 두가지 방법을 소개합니다. reduce()와 concat()을 이용하여 2차원 배열을 1차원으로 변환할 수 있습니다. 배열을 순회하면서 concat()으로 요소
codechacha.com
배열을 객체로 변환
https://codechacha.com/ko/javascript-convert-array-to-object/
JavaScript - 배열을 객체로 변환, 4가지 방법
Object.assign(target, source)는 source의 내용을 target에 복사합니다. 아래와 같이 배열을 source로 전달하면 Index가 key가 되고, 배열의 요소가 value로 이루어진 객체가 생성됩니다. Spread operator를 이용하여
codechacha.com
'JavaScript' 카테고리의 다른 글
JS REGREX 정규식 표현 공부하기 (유튜브 videoId 추출 정규식 표현) (0) | 2022.07.22 |
---|---|
JS - Back에서 보내주고 Front 에서 Data 받는 구조 공부하기 (0) | 2022.03.04 |
JavaScript - 배열함수(map, push..) (0) | 2022.02.16 |
| && || 차이점 (0) | 2022.02.02 |
N차 다항식 예제 (0) | 2021.12.28 |