js array object operation methods, usage scenarios

JavaScript recursively generates a JSON tree by parent node ID:

Implementation idea: Implemented through recursion (query all parent nodes during the first recursion, and then continuously query all child nodes through the current parent node ID until the recursion is completed and returned)

// 模拟数据
const ary = [
    { id: '1', name: '11', parent_id: '' },
    { id: '2', name: '22', parent_id: '' },
    { id: '3', name: '33', parent_id: '' },
    { id: '11', name: '11-11', parent_id: '1' },
    { id: '12', name: '11-12', parent_id: '1' },
    { id: '21', name: '22-21', parent_id: '2' },
    { id: '31', name: '33-31', parent_id: '3' },
]

/**
 * 递归通过父节点ID生成树结构
 * 思路:
 *      1. 第一次递归的时候查询出所有的父节点
 *      2. 然后通过当前父节点id不断地去查询所有子节点,直到递归完毕返回
 * @param {
     
     String} pid 父节点id
 */
function getTrees(pid='') {
    if(!pid) {
        // 如果没有父id(第一次递归的时候)将所有父级查询出来
        return ary.filter(item => !item.parent_id).map(item => {
            // 通过父节点ID查询所有子节点
            item.children = getTrees(item.id)
            return item
        })
    } else {
        return ary.filter(item => item.parent_id === pid).map(item => {
            // 通过父节点ID查询所有子节点
            item.children = getTrees(item.id)
            return item
        })
    }
}

console.log(getTrees()) 
/** 输出:
 * [{
 *  id: "1",
 *  name: "11",
 *  parent_id: 0,
 *  children: [
 *    {
 *      id: "11",
 *      name: "11-11",
 *      parent_id: '1',
 *    }
 *  ]
 * },......]
*/

JS changes object property name in array

The object attribute names in the array that the backend responds to the frontend are not what we want, and can be converted through this method.
After the conversion, the original response body has not changed.

	const data = {
		totalEmelents: 100,
		list: [
		   { id: 0, name: "a" },
		   { id: 1, name: "b" },
		   { id: 2, name: "c" },
		]
	}
	
	const myList = data.list.map(item => {
		return {
			key: item.id,
			value: item.name
		}
	});

	console.log(...data.list)	
	console.log(...myList)
{
    
    id: 0, name: 'a'} {
    
    id: 1, name: 'b'} {
    
    id: 2, name: 'c'}//原来的
{
    
    key: 0, value: 'a'} {
    
    key: 1, value: 'b'} {
    
    key: 2, value: 'c'}//修改之后的

Modify the attribute name in children

 Use for loop method

const list = [
  { id: 0, name: "a", children: { id: 100, name: 'dd' } },
  { id: 1, name: "b" },
  { id: 2, name: "c" }
];

for (let i = 0; i < list.length; i++) {
  if (list[i].children) {
    list[i].children.pid = list[i].children.id;
    delete list[i].children.id;
  }
}

console.log(list);

打印结果:[
  { id: 0, name: 'a', children: { name: 'dd', pid: 100 } },
  { id: 1, name: 'b' },
  { id: 2, name: 'c' }
]

 Use map method

const list = [
  { id: 0, name: "a", children: { id: 100, name: 'dd' } },
  { id: 1, name: "b" },
  { id: 2, name: "c" }
];

const modifiedList = list.map(({ id, name, children }) => ({
  id,
  name,
  children: children ? { pid: children.id, name: children.name } : undefined
}));

console.log(modifiedList);

打印结果[
  { id: 0, name: 'a', children: { name: 'dd', pid: 100 } },
  { id: 1, name: 'b' },
  { id: 2, name: 'c' }
]

 Practice test questions

The question and answer are copied from Niuke.com. The answer is not the simplest, but it can just be applied to the JS object method.

++ String character statistics (Niuke.com)

Topic description:

Count the frequency of occurrence of each character in the string and return an Object. The key is the statistical character and the value is the frequency of occurrence.

  1. No restriction on the order of keys
  2. The input string parameter will not be empty
  3. Ignore whitespace characters

enter:

‘hello world’

Output:

{h: 1, e: 1, l: 3, o: 2, w: 1, r: 1, d: 1}

Answer: ( Need more? )


function count(str) {
	//用正则表达式去除空白符
    var newStr = str.replace(/\s/g,"");
    //console.log(newStr) //helloworld
    var res={};
    for(var i=0 ; i<newStr.length; i++){
    	//循环字符串,判断是否已存在对象中
        if(newStr.charAt(i) in res){
            res[newStr.charAt(i)]++;
        } 
        else{
            res[newStr.charAt(i)] = 1;
        }
    }
    return res;
}
count('hello world')

++ Time formatted output (Niuke.com)

Topic description:

Output the specified time according to the given time format.
Format description:
For 2014.09.05 13:14:20
yyyy: year, 2014
yy: year, 14
MM: month, filled with two digits, 09
M: month, 9
dd: date, Fill two digits, 05
d: date, 5
HH: 24-hour hour, fill two digits, 13
H: 24-hour hour, 13
hh: 12-digit hour, fill two digits, 01
h: 12-hour hour, 1
mm : minute, filled with two digits, 14
m: minute, 14
ss: second, filled with two digits, 20
s: second, 20
w: week, which is ['day', 'one', 'two', 'three' , 'four', 'five', 'six'], the result of this demo is five

enter:

formatDate(new Date(1409894060000), ‘yyyy-MM-dd HH:mm:ss 星期w’)

Output:

2014-09-05 13:14:20 Friday

Answer: ( Need more? )

function formatDate(t,str){
  var obj = {
    yyyy:t.getFullYear(),
    yy:(""+ t.getFullYear()).slice(-2),
    M:t.getMonth()+1,
    MM:("0"+ (t.getMonth()+1)).slice(-2),
    d:t.getDate(),
    dd:("0" + t.getDate()).slice(-2),
    H:t.getHours(),
    HH:("0" + t.getHours()).slice(-2),
    h:t.getHours() % 12,
    hh:("0"+t.getHours() % 12).slice(-2),
    m:t.getMinutes(),
    mm:("0" + t.getMinutes()).slice(-2),
    s:t.getSeconds(),
    ss:("0" + t.getSeconds()).slice(-2),
    w:['日', '一', '二', '三', '四', '五', '六'][t.getDay()]
  };
  return str.replace(/([a-z]+)/ig,function($1){
    
    return obj[$1]});
}

formatDate(new Date(1409894060000), 'yyyy-MM-dd HH:mm:ss 星期w')
//"2014-09-05 13:14:20 星期五"

Encountered in the project

JS query certain words in the string and add styles, tags, and strings to it

 

 ++ Array deduplication

Topic description:

Add a method to the Array object to remove duplicates

enter:

[false, true, undefined, null, NaN, 0, 1, {}, {}, ‘a’, ‘a’, NaN]

Output:

[false, true, undefined, null, NaN, 0, 1, {}, {}, ‘a’]

Answer: ( Need more? )

Array.prototype.uniq = function () {
   var resArr = [];
   var flag = true;
   for(var i=0;i<this.length;i++){
       if(resArr.indexOf(this[i]) == -1){
           if(this[i] != this[i]){   //排除 NaN
              if(flag){
                   resArr.push(this[i]);
                   flag = false;
              }
           }else{
                resArr.push(this[i]);
           }
       }
   }
    return resArr;
}
var arr = [false, true, undefined, null, NaN, 0, 1, {}, {}, 'a', 'a', NaN];
arr.uniq()//[false, true, undefined, null, NaN, 0, 1, {}, {}, 'a']
++ Convert string to camel case format

Topic description:

There are often characters like background-image in css connected by -. When setting the style through javascript, you need to convert this style into backgroundImage camel case format. Please complete this conversion function.

  1. Using - as the delimiter, convert the first letter of the second non-empty word to uppercase
  2. -webkit-border-image The converted result is webkitBorderImage

enter:

‘font-size’

Output:

fontSize

Answer: ( Need more? )

function cssStyle2DomStyle(sName) {
    let sNameArr = sName.split(''); //["f", "o", "n", "t", "-", "s", "i", "z", "e"]
    if(sNameArr.indexOf('-')==0){
        sNameArr.splice(0,1)//删除连接符'-'
    }
    for(var i=1; i<sNameArr.length; i++){
        if(sNameArr[i] == '-'){
            sNameArr.splice(i,1);//删除连接符'-'
            sNameArr[i]=sNameArr[i].toUpperCase();//将首个单词转换成大写
        }
    }
    return sNameArr.join('');
}
cssStyle2DomStyle('font-size')//fontSize

Guess you like

Origin blog.csdn.net/qq_43319351/article/details/131503438