nodejs列表和对象

nodejs基础扫盲

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

纯纯为了以后自己回忆方便。各位网友不要看,对你们没有任何帮助。


列表

一般来说列表可以是[{
    
    },{
    
    },{
    
    }]{
    
    }是字典,也就是json

nodejs读取数据的结果就是 [{},{},{}]这种形式。
在这里插入图片描述
那要怎么读取这种数据呢?

const array = [{
    
    }, {
    
    }, {
    
    }];
array.forEach(item => {
    
    
  console.log(item);
});

for (const a of array) {
    
    
    console.log(a)
}

const array = [{
    
    }, {
    
    }, {
    
    }];
for (const index in array) {
    
    
    console.log(array[index]);
}

const array = [1, 2, 3];
const newArray = array.map(item => item * 2);
console.log(newArray); // 输出: [2, 4, 6]

过滤数组

假设你有一个数组,你想根据某些条件过滤出符合条件的元素:

const array = [{
    
     id: 1, name: 'Alice' }, {
    
     id: 2, name: 'Bob' }, {
    
     id: 3, name: 'Charlie' }];

// 过滤出名字是'Bob'的元素
const filteredArray = array.filter(item => item.name === 'Bob');

console.log(filteredArray); // 输出: [{ id: 2, name: 'Bob' }]

此时我们有了新的需求
过滤出名字是'Bob'的元素,然后取出name

const array = [{
    
     id: 1, name: 'Alice' }, {
    
     id: 2, name: 'Bob' }, {
    
     id: 3, name: 'Charlie' }];

const filteredNames = array
  .filter(item => item.name === 'Bob')
  .map(item => item.name);

console.log(filteredNames); // 输出: ['Bob']

对象

一般来说列表可以是{
    
    x: {
    
    }, x1: {
    
    }}{
    
    }是字典,也就是json

对于 {x: {}, x1: {}},可以用 for…in 遍历属性:

const obj = {
    
    x: {
    
    }, x1: {
    
    }};
for (const key in obj) {
    
    
  console.log(key, obj[key]);
}

Object.keys(obj).forEach(key => {
    
    
    console.log(key, obj[key]);
});

过滤对象

对象本身不支持直接过滤,但我们可以将对象转换为数组、过滤,然后再转换回对象。假设有一个对象,当我们想根据某些条件过滤出符合条件的键值对:

const obj = {
    
     x: {
    
     age: 25 }, y: {
    
     age: 30 }, z: {
    
     age: 18 } };
const m = Object.entries(obj);
console.log(m);
//[ [ 'x', { age: 25 } ], [ 'y', { age: 30 } ], [ 'z', { age: 18 } ] ]


// 过滤出年龄大于20的键值对
const filteredEntries = Object.entries(obj).filter(([key, value]) => value.age > 20);
console.log(filteredEntries);
//[ [ 'x', { age: 25 } ], [ 'y', { age: 30 } ] ]
// Object.entries() 返回一个数组,每个元素是一个 [key, value] 对。
// 转换回对象
const filteredObj = Object.fromEntries(filteredEntries);

console.log(filteredObj); // 输出: { x: { age: 25 }, y: { age: 30 } }


总结

  • 数组:使用 filter 方法。
  • 对象:将对象转换为数组 (Object.entries),过滤,然后转换回对象(Object.fromEntries)。

猜你喜欢

转载自blog.csdn.net/hola173841439/article/details/141728355